Results 1 to 4 of 4
- 04-23-2008, 06:31 AM #1
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.
Please help me.Java 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, 07:23 AM #2
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,374
- Blog Entries
- 1
- Rep Power
- 18
Initially x = 5.0
Call the power() with x = 5.0 and n = 4. Those parameters are moving on the loop as follows.Java Code:double x = 5.0;
So the answer is 625.0 for the first println(). Hope it's help :)Java 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
- 04-23-2008, 07:34 AM #3
Thanks a lot Eranga.
if we take the visual of above code.it is chain loop. is it Eranga?
- 04-23-2008, 08:08 AM #4
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,374
- Blog Entries
- 1
- Rep Power
- 18
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.
Similar Threads
-
Help With Recursion
By andrew777 in forum New To JavaReplies: 1Last Post: 03-29-2008, 12:51 PM -
recursion
By kdeighan in forum New To JavaReplies: 3Last Post: 01-25-2008, 09:48 PM -
Recursion
By bozovilla in forum Advanced JavaReplies: 3Last Post: 01-07-2008, 04:53 PM -
Help with recursion
By scts102 in forum New To JavaReplies: 1Last Post: 11-19-2007, 10:07 PM -
Recursion in java
By lenny in forum Advanced JavaReplies: 1Last Post: 08-07-2007, 06:23 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks