Thursday, March 23, 2017

Fibonacci Series (Looping and Recursion)

This is a part of Interview Preparation Series I am preparing.

Today in this article we are going to discuss about Fibonacci series.

It's better if you have some idea about Recursion.

The code below has both the for loop way and the recursive way.


public class Fibonnaci {
// Output = 0 1 1 2 3 5 8 13
public static void main(String args[]){
int num = 20;
int fibSeries[] = fib(num);
System.out.println("Fibonacci by For loop:");
for (int i = 0; i < fibSeries.length; i ++){
System.out.print(fibSeries[i] + " ");
}
System.out.println("");
int fibSeriesRec[] = fibByRec(num);
System.out.println("Fibonacci by Recursion:");
for (int i = 0; i < fibSeriesRec.length; i ++){
System.out.print(fibSeriesRec[i] + " ");
}
}
public static int[] fibByRec(int num){
int fib[] = new int[num];
for (int i = 0 ; i < num; i ++){
fib[i] = fibRec(i);
}
return fib;
}
public static int[] fib(int num){
int fib[] = new int[num];
for(int i = 0; i < num; i ++){
if ( i == 0){
fib[i] = i;
continue;
}
if ( i == 1 || i == 2){
fib[i] = 1;
continue;
}
fib[i] = fib[i-1] + fib [i - 2]; 
}
return fib;
}
public static int fibRec(int num){
if(num == 0){
return 0;
}
else if (num == 1 || num == 2){
return 1;
}else {
return fibRec(num -1 ) + fibRec(num - 2);
}
}

}

The output:

Fibonacci by For loop:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 

Fibonacci by Recursion:

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 

No comments:

Post a Comment