CRX-Recursion (power)

unable to understand below shared code… how it is working in the code?
int pnm1 = power( x, n-1);

@vashisthdeepak928,

int pnm1 = power( x, n-1);

Here we are calling the power function again with the arguments x and n-1.

Now try to relate with the above picture. From pow(2,5) we go till pow(2,1). And at pow(2,1) when we execute the line int pnm1 = power( 2, 1-1); we get 0 since the function returns 1 when n becomes 0.

Now the int pnm1 = power(2,1), here pnm1 has value 1. In the next line we have, int pn = 2*pnm1, therefore pn=2; and we return 2 from power(2,1).

Now we made the call for power(2,1) from the code when power(2,2) was being executed.
Hence, inside power(2,2)
We get int pnm1 = power(2,1) =2;
int pn = 2*2 = 4
now we return 4 from power(2,2).
And so on we go till power(2,5) and finally return the answer 32.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.