Java Fibonaci with and without recursion

In a series of number upto n Fobonaci is addition if n-1 and n-2 number.We have implemented the fibonaci code below using recursion and without recursion. In most interviews they ask fibonaci with recursion so have a look below.


public class Test2 {
	
	public static void main(String[] args) {
		int i =5;
		//0,1,1,2,3,5,8,13,21
	System.out.println("With Recursion--"+fibonaci(i));
		System.out.println("\n---- With Recursion"+fibonaciRec(i));
	}
	

	public static double fibonaci(int n) {
		 double t1 = 0, t2 = 1;
		 double sum =0;
		   for (int i = 1; i < n; ++i)
	        {
	     //       System.out.print(t1 + " + ");

	             sum = t1 + t2;
	            t1 = t2;
	            t2 = sum;
	        }
		   return sum;
			
	}
	public static double fibonaciRec(int n) {
		
		if (n<2)
			return n;
		
		else 
			return fibonaciRec(n-1) +fibonaciRec(n-2);
		
			
	}
}


Previous
Next Post »

Pages