Help with a detail explanation of Recursion Code

public static void main (String[] args){

int n1 = 0, n2 = 1, n3 = 0;

System.out.println("n1 = " +n1);

fib(n1, n2);
}

public static void fib(int n1, int n2)
{

System.out.println("n2 = " +n2);

n3 = n2;

n2 = n1 + n2;

n1 = n3;

fib(n1, n2);

}

Fibonacci sequence is a sequence whose any element is the sum of previous two elements. (Exclude the first 2 elements :0,1)

This code prints fibonacci sequence.

The first element is 0 which is printed in main itself. After that function fib() is called. In this function n3 is used as a temporary variable to store current value of n2. Now n2 is changed to sum of the two input numbers. Further n1 is updated to the previous value of n2.

Consider following example:

Suppose at any instance you passed (1,2) in fib() then it would print 2. After that it would change the second number to 2+1=3 and the first number to 2. Now function fib is recursively called with (2,3) as parameters. This process will keep going on.

1 Like