Page 401 - Computer science 868 Class 12
P. 401
Dry run/Working
Counter Condition Executable Statements Output Counter next
value value
3 3 = 0 false mymethod(3) Hello 3 Step 3 popping 2
System.out.println(" "+2) mymethod(3)
2 2 = 0 false mymethod(2) Hello 2 Step 2 popping 1
System.out.println(" "+1) mymethod(2)
1 1 = 0 false mymethod(1) Hello 1 Step 1 popping 0
System.out.println(" "+0) mymethod(1)
0 0 = 0 true Base case reached. Blank print
Now stack is popped
counter Counter = 0 Push in stack Output pushing Popping Output popping
Question 2: What will be the output of the following recursive code when a = 6 and b = 14. Also predict what the
method is computing?
class recEx1
{
int guess(int x, int y) {
if (y == 0)
return 0;
else if (y % 2 == 0)
return guess(x+x, y/2);
else
return guess(x+x, y/2) + x;
}
}
Condition Executable Output Counter next value
Statements
st
0 = 0 true return 0 1 method popped 0
Base case
nd
1 = 0 false 1%2 = 0 false return 2 method popped 0 + 48 = 48
guess (96, 0) + 48
rd
3 = 0 false 3%2 = 0 false return 3 method popped 48 + 24 =72
guess (48, 1) + 24
7 = 0 false 7%2 = 0 false return 4 method popped 72 + 12 = 84
th
guess (24, 3) + 12
14 = 0 false 14%2 = 0 true return last method popped Value returned 84
guess (12, 7) stack empty
y = 0 y%2 = 0 return Output
The above method is printing the product of a and b.
399
Recursion 399

