# i could not get the recursion in java

• 04-23-2008, 07:31 AM
sivasayanth
i could not get the recursion in java
I have just studied one java source code. That entirely belongs to recursion in java. However, I could not understand what happened in the execution sequence.
Code:

```public class MainClass {   public static void main(String[] args) {     double x = 5.0;     System.out.println(x + " to the power 4 is " + power(x, 4));     System.out.println("7.5 to the power 5 is " + power(7.5, 5));     System.out.println("7.5 to the power 0 is " + power(7.5, 0));     System.out.println("10 to the power -2 is " + power(10, -2));   }   // Raise x to the power n   static double power(double x, int n) {     if (n > 1)       return x * power(x, n - 1); // Recursive call     else if (n < 0)       return 1.0 / power(x, -n); // Negative power of x     else       return x;   } }```
What is the return value When first execution happened?
• 04-23-2008, 08:23 AM
Eranga
Initially x = 5.0

Code:

`double x = 5.0;`
Call the power() with x = 5.0 and n = 4. Those parameters are moving on the loop as follows.
Code:

```on if clause - still n > 1(n = 4) so,       return 5.0 * power( 5.0, 3) on if clause - still n > 1(n = 3) so,         5.0 * return 5.0 * power( 5.0, 2) on if clause - still n > 1(n = 3) so,         5.0 * 5.0 * return 5.0 * power( 5.0, 1) skip else-if clause - n is not a negative on else clause       5.0 * 5.0 * 5.0 * return 5.0```
So the answer is 625.0 for the first println(). Hope it's help :)
• 04-23-2008, 08:34 AM
sivasayanth
Thanks a lot Eranga.

if we take the visual of above code.it is chain loop. is it Eranga?
• 04-23-2008, 09:08 AM
Eranga
Yes, kind of a chain loop. Simply do the same process(what we called looping) until certain condition is satisfied and keep track of certain data.

Here you can see that the value of x behave like that.