Re: Simple recursion logic

Remember, you have to traverse down to the lowest level before back-tracing in a recursive algorithm.

So, the first recursive call would be:

sum(4) = 4 + sum(3-1)

sum(3) = 3 + sum(3-1)

sum(2) = 2 + sum(2-1)

sum(1) = 1

So, the end result is:

sum(4) = 4 + 3 + 2 + 1

This doesn't really illustrate the order operations are done, though. Instead, the computer would evaluate it this way:

sum(4) = 4 + (3 + (2+ (1)))

So, the number 7 never shows up.

Re: Simple recursion logic

A recursive call is just like any other method call:

Code :

public int ReturnOne() {
return 1;
}
public static void main(String[] args) {
int two = ReturnOne() + ReturnOne();
System.out.println(two);
}

In the above the result of the two is initially null then it's 1 after the first method call, then it's two after the second method call. While the method calls are made the intermediate value of two is stored on a call stack by the java virtual machine.

The same applies for recursion. In your case this is what happens:

Code :

the method sum(int n) is called with value 4
return value stored on stack is 4
method sum(int n) is called with value 3
return value stored on stack is 3
method sum(int n) is called with value 2
return value stored on stack is 2
method sum(int n) is called with value 1
return value is 1
return value is (stack value) 2 + (returned value) 1 = 3
return value is (stack value) 3 + (returned value) 3 = 6
return value is (stack value) 4 + (returned value) 6 = 10

Re: Simple recursion logic

ahh so thats how recursion process works...

im just confuse where does the value go every time it evaluates....

so thats it... tnx guys...