Recursive Fibonacci in Java


Recursion.java

public class Recursion {
	
	public static void main(String[] args) {
		int n1 = 0;
		int n2 = 1;
		System.out.println(n1);
		System.out.println(n2);
		doRecursion(n1, n2); //Doing Recursion Here
	}
	
	public static int doRecursion(int n1,int n2){
		int n3 = n1+n2; // Dynamic allocation of values
		System.out.println(n3);
		n1 = n2;
		n2 = n3;
		if(n3 > 40){ // Exit condition
			return 0;
		}
		return doRecursion(n1,n2);
	}
}

Output

[su_box title=”Output for Recursion.java”]0 1 1 2 3 5 8 13 21 34 55[/su_box]