Reputation: 13
I have a Java class in my High School, and as one of the practice problems, we had to trace this recursive program:
public class Loop {
public static void main(String[] args) {
double x = okay(6, 1.5);
System.out.println("x is" + x);
}
public static double okay(int w, double z) {
System.out.println(w + "," + z);
if (z > -15) {
return okay(w += 3, z - w) - z;
} else
return 12;
}
}
I had traced this program correctly except for the last line. My teacher had said that my final answer(I wrote 12.0) was incorrect, and that the correct answer was 16.0. I would highly appreciate if one of you guys would explain how this works for me. Thanks in advance.
Upvotes: 1
Views: 66
Reputation: 26530
Tracing down the recursive calls:
x = okay(6, 1.5)
System.out.println(6 + "," + 1.5)
=> "6,1.5"return okay(6, (1.5 - 9)) - 1.5
System.out.println(6 + "," + -7.5)
=> "6,-7,5"return okay(6, (-7.5 - 9)) - -7.5
System.out.println(6 + "," + -16.5)
=> "6,-16.5"return 12
Then, going back up the chain:
return 12
return 12 - -7.5
=> 19.5return 19.5 - 1.5
=> 18.0x = 18.0
System.out.println("x is" + 18.0);
=> "x is 18.0"Upvotes: 3
Reputation: 2455
You can view it like :
okay(6,1.5)
okay(9,-7.5) - 1.5
okay(12,-16.5) - (-7.5)
return 12 + 7.5
return 19.5 - 1.5
18.0
To understand better view this question too : Java recursion Understanding
Upvotes: 1
Reputation: 26185
I agree with the previous answers. One way to make it easier to see what is going on is to add a printout for the return values:
public static double okay(int w, double z) {
System.out.println(w + "," + z);
if (z > -15) {
double result = okay(w += 3, z - w) - z;
System.out.println("Returning "+result);
return result;
} else
System.out.println("Returning 12");
return 12;
}
The output is:
6,1.5
9,-7.5
12,-19.5
Returning 12
Returning 19.5
Returning 18.0
x is18.0
Upvotes: 0
Reputation: 17707
You are all wrong ... the answer is 18.0 .....
The best way to solve this problem is copy/paste the code in to your favourite IDE, and to run it....
In my case, it gives the output:
6,1.5
9,-7.5
12,-19.5
x is18.0
And, I presume Java is right in this case.
Upvotes: 1