In: Computer Science
What would be the result of each of the following programs?
1 |
public class
RecursionInJava1{ } Public static int guess(int num){ if (num == 1) return 0; else return (guess(num-2)-num); } } |
|
2 |
public class
RecursionInJava2{ } } } |
Please find the answers for your questions below and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
Answer for question 1:
The program will output -24.
Explanation:
Let’s go through each recursive call of the method guess().
Initially the value passed is 9.
guess(9) :- Since 9 is not 1, else block gets executed which will call guess(9-2) and subtract 9 from it before returning it. So the method will return guess(7)-9
guess(7) :- Since 7 is not 1, else block gets executed which will call guess(7-2) and subtract 7 from it before returning it. So the method will return guess(5)-7
guess(5) :- Since 5 is not 1, else block gets executed which will call guess(5-2) and subtract 5 from it before returning it. So the method will return guess(3)-5
guess(3) :- Since 3 is not 1, else block gets executed which will call guess(3-2) and subtract 3 from it before returning it. So the method will return guess(1)-3
guess(1) :- Since 1 is equal to 1, this method simply returns 0
Combining all the return statements, we get
(((((0)-3)-5)-7)-9) => -24
Answer for question 2:
The program will output 27
Explanation:
Let’s go through each recursive call of the method sum().
Initially the value passed to sum() from the main is 10.
sum(10) :- Since 10 is not 7, sum(10-1)+10 or sum(9)+10 is returned
sum(9) :- Since 9 is not 7, sum(9-1)+9 or sum(8)+9 is returned
sum(8) :- Since 8 is not 7, sum(8-1)+8 or sum(7)+8 is returned
sum(7) :- Since 7 equals 7, 0 is returned
Combining all the return statements, we get
((((0)+8)+9)+10) = 27