Reputation: 45
I saw this code online but what I am asking is how did the program come up with an answer of 12
?
I did a tracing of the program, and I only come up with an answer of 6
.
Why is the answer 12
?
The inputs are a=6
and b=6
.
This is the code:
public static int addxy(int a, int b)
{
if (a==0)
return b;
else if (b==0)
return a;
else
return 1 + addxy(a, b-1);
}
Upvotes: 2
Views: 1363
Reputation: 2934
Upvotes: 2
Reputation: 7730
As @Mureinik answer is perfect but you didn't understand it ,
So Lets start with a very basic example of Calculating Factorial via Recursion:
public int factorial(int num){
if(num==0) //break condition of Recursion Since 0! is always 1
return 1;
return num*fact(num-1);
}
So here is the Tracing
factorial(4) return 4*factorial(3);
factorial(3) return 3*factorial(2);
factorial(2) return 2*factorial(1);
factorial(1) return 1*factorial(0);
factorial(0) returns 1;
, Now backtrace this answers and this below image is formed
May Be now you are able to understand it
Upvotes: -1
Reputation: 5853
Look at the return
statement
return 1 + addxy(a, b-1);
You have a function call in the return
statement to the same function. This is called a recursive function
. So as long as b is not 0
, it keeps on calling it again n again but by adding 1
and subtracting b
by 1
. This goes on till b
becomes 0
. Which is 6 times. And thats why you get 1*6 + a = 6
Equivalent execution would be
return 1 + addxy(6, 5);
return 1 + 1 + addxy(6, 4);
return 1 + 1 + 1 + addxy(6, 3);
return 1 + 1 + 1 + 1 + addxy(6, 2);
return 1 + 1 + 1 + 1 + 1 + addxy(6, 1);
return 1 + 1 + 1 + 1 + 1 + 1 + addxy(6, 0);
return 1 + 1 + 1 + 1 + 1 + 1 + 6; // Value of a = 6
return 12;
Upvotes: 0
Reputation: 279940
This
return 1 + addxy(a, b-1);
returns 1
plus the result of calling the method recursively while removing 1
from b
. This basically means that it adds b
.
When b
is 0
, you return a
.
else if (b==0)
return a;
(You also return b
, when a
is 0
.
Without even tracing anything, you can tell that (with non-negative values for a
and b
) the method simply adds a
and b
and returns the result.
Upvotes: 0
Reputation: 311188
Try walking over it step by step:
addxy(6, 6) returns 1 + addxy(6, 5)
addxy(6, 5) returns 1 + addxy(6, 4)
addxy(6, 4) returns 1 + addxy(6, 3)
addxy(6, 3) returns 1 + addxy(6, 2)
addxy(6, 2) returns 1 + addxy(6, 1)
addxy(6, 1) returns 1 + addxy(6, 0)
addxy(6, 0) returns 6
So, addxy(6, 1) returns 1 + 6 = 7
So, addxy(6, 2) returns 1 + 7 = 8
So, addxy(6, 3) returns 1 + 8 = 9
So, addxy(6, 4) returns 1 + 9 = 10
So, addxy(6, 5) returns 1 + 10 = 11
So, addxy(6, 6) returns 1 + 11 = 12
Upvotes: 1