Well, this is another question taken from this practice exam that was given to me that I just don’t know what to do with.
int fun5 (int c, int d) {
if (c <= d) {
return c;
} else {
return fun5(c-d, d) * c;
}
}
When you run the code with value of fun5(9,3), you’re supposed to get 162, but I have not idea how to get there. Obviously the first if statement is false, so you go to the else, but then you have to go back to fun5 with those new values, but then the if statement fails again, so you go to the else again, but you just came from there. I’m just a very confused person right now.
It’s recursion
The first time c=9 and d=3 so you do the else statement: (below with the numbers substituted)
Then you do the next go with c=6 and d=3 so you do the else again
Then you do the next one with c=3 and d=3 so you do the if
Follow it up the stack you get
Final return is 18 * 9 or 162.