+ 4
help w/ recursion -returns 95 but why not 99?
this code returns 95 but i would expect it to return 99. can anyone explain please ? public class Program { public static int cbse(int x){ if (x < 100){ //System.out.println(x); x = cbse(x + 10); //System.out.println(x); } return x - 1; } public static void main(String[] args) { int free = cbse(60); System.out.println(free); } }
7 ответов
+ 14
cbse(60) => return 96-1=95 (final result)
\ 1) /8)
cbse(70) => return 97-1=96
\ 2) /7)
cbse(80) => return 98-1=97
\ 3) /6)
cbse(90) =>return 99-1=98
\ 4) /5)
cbse(100) => return 100-1=99
might be helpful to see how its happening in more simple way, steps are numbered.
+ 8
Performing a dry run, we have:
Initial : cbse(60)
-> cbse(70)-1
// since the value returned is x-1, and x
// was the value returned by cbse(70)
-> cbse(80)-2
// evaluation of cbse(70) = cbse(80)-1.
// Thus cbse(60) =
// (cbse(80)-1)-1 = cbse(80)-2
-> cbse(90)-3
// Continuing with above pattern
-> cbse(100)-4
Now, cbse(100) is 100-1 = 99.
So the answer is 99-4 = 95.
+ 2
thank you for the quick response. i am still somewhat confused. why does x retain the state of x - 1 if it is not getting called until the condition is met?
+ 2
The -1 is not from the final return statement, but the return statement from another call to the function.
The compiler saved the value of cbse(70) in x, evaluated it and proceeded to the return statement. So cbse(60) becomes cbse(70)-1. Now cbse(70) must have also evaluated some x and returned it after subtracting 1. So the value of x is modified accordingly.
+ 2
i believe it is starting to sink in. thank you so much.
+ 2
the best comparison i can think of is like the movie ‘Inception’ where it keeps going one level deeper and deeper until they need to come back completely, then they still have to run up the dream stack or stack lol. i definitely got it now. thank you!
0
Y