In: Computer Science
For each call to the following method, indicate what console output is produced:
public void mystery2(int n) { if (n <= 1) { System.out.print(n); } else { mystery2(n / 2); System.out.print(", " + n); } }
mystery2(1); | |
mystery2(4); | |
mystery2(16); | |
mystery2(30); | |
mystery2(100); |
Solution:
Here in the given mystery2() function it is checking whether the n value is less than or equals to 1 if yes print(n) value otherwise call mystery2() by dividing n with 2 . Here after the function call the print statement will execute.
when we call mystery2(1) it will print the value 1 because n<=1 is becomes true so it will print 1.
when we call mystery2(4) it will print 1,2,4
because here n=4 so n<=1 becomes false so it will call mystery2(n/2) = mystery2(2) after execution of mystery2(1) it will print value 4
so in next step n=2 so n<=1 becomes false so it will call mystery2(2/2)= mystery2(1) after execution of mystery2(1) it will print value 2
Here n=1 so n<=1 becomes true so it will print value 1 and executes the print statements after the previous recursive calls.
n | Condition | func call | remaining statements need to execute |
mystery2(4) | |||
4 | 4<=1 false | mystery2(4/2) | print(n) =4 |
2 | 2<=1 false | mystery2(2/2) | print(n)=2 |
1 | 1<=1 true | print(n)=1 |
i.e 1,2,4
when we call mystery2(16) output is 1,2,4,8,16
so
n | Condition | func call | remaining statements need to execute |
mystery2(16) | |||
16 | 16<=1 = false | mystery2(16/2) | print(n) = 16 |
8 | 8<=1 false | mystery2(8/2) | print(n) =8 |
4 | 4<=1 false | mystery2(4/2) | print(n) =4 |
2 | 2<=1 false | mystery2(2/2) | print(n)=2 |
1 | 1<=1 true | print(n)=1 |
when we call mystery2(30) output is 1,3,7,15,30
n | Condition | func call | remaining statements need to execute |
mystery2(30) | |||
30 | 30<=1 = false | mystery2(30/2) | print(n) = 30 |
15 | 15<=1 false | mystery2(15/2) | print(n) =15 |
7 | 7<=1 false | mystery2(7/2) | print(n) =7 |
3 | 3<=1 false | mystery2(3/2) | print(n)=3 |
1 | 1<=1 true | print(n)=1 |
when we call mystery2(100) output is 1,3,6,12,25,50,100
n | Condition | func call | remaining statements need to execute |
mystery2(100) | |||
100 | 100<=1 = false | mystery2(100/2) | print(n) = 100 |
50 | 50<=1 false | mystery2(50/2) | print(n) =50 |
25 | 25<=1 false | mystery2(25/2) | print(n) =25 |
12 | 12<=1 false | mystery2(12/2) | print(n)=12 |
6 | 6<=1 false | mystery2(6/2) | print(n)=6 |
3 | 3<=1 false | mystery2(3/2) | print(n)=3 |
1 | 1<=1 true | print(n)=1 |
Note:Here remaining statements will execute from bottom to top. Also print statement includes commas.
mystery2(1) = 1
mystery2(4) = 1, 2, 4
mystery2(16) = 1, 2, 4, 8, 16
mystery2(30) =1, 3, 7, 15, 30
mystery2(100) = 1, 3, 6, 12, 25, 50, 100
Note: if you have any queries please post a comment thanks a lot.. always avaiable to help you...