Link to home
Start Free TrialLog in
Avatar of gudii9
gudii9Flag for United States of America

asked on

java recursion example

Hi,

I am reading below link on java recursion

https://howtoprogramwithjava.com/java-recursion/

i wonder how and where n2 gets incremented to print fibonacci numbers as below
0,1,1,2,3,5...
please advise
ASKER CERTIFIED SOLUTION
Avatar of dpearson
dpearson

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Agree with what Doug says, but most people start with factorial demonstration, as that is quite well known, whereas Fibonacci is a little more intricate. So here is a simple factorial recursion.

class Recur {

public static void main(String[] args){

Recur recur = new Recur();

System.out.println(recur.recurer(10));

}

static int recurer(int i){

		System.out.println(i==1?" . . . being called for the last time":" - > Call number "+(10-i+1)+".");

		if (i <= 1) {
	      return 1;
		}
	
	return i * recurer(i-1);
}


}

Open in new window

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
https://howtoprogramwithjava.com/java-recursion/

Actually, the code you are quoting has an index output error - line 23, as it stands in the original, should be transported up to line 5, otherwise the indexes are not printed sequentially.

Line 23 fyi, is
index++;

Open in new window

i wonder how and where n2 gets incremented
fibonacciSequence(n2, n1+n2);  
// but it's not incremented because it is passed to a different n2
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial