Number series in which next number is the sum of previous two numbers is called Fibonacci Series
Example : 0, 1, 1, 2, 3, 5, 8, 13, etc.
Fibonacci Series in Java can be written in following two ways :
1) Without Recursion
2) With Recursion
Following two programmes illustrate Fibonacci Series Using Recursion & without using Recursion
1) Java Program For Fibonacci Series Using Recursion
public class fibonacciRecMethod {
public static int fibonacciRecMeth(int count) {
if (count == 0) {
return 0;
}
if (count == 1 || count == 2) {
return 1;
}
return fibonacciRecMeth(count - 1) + fibonacciRecMeth(count - 2);
}
}
public class FibonacciRec {
public static void main(String args[]) {
int series_count = 9;
System.out.print("Fibonacci Series For First " + series_count + " numbers is: \n");
for (int i = 0; i < series_count; i++) {
System.out.print(fibonacciRecMethod.fibonacciRecMeth(i) + " ");
}
}
}
Output :
Fibonacci Series For First 9 numbers is:
0 1 1 2 3 5 8 13 21
2) Java Program For Fibonacci Series Without Using Recursion
public class FibonacciWithoutRec {
public static void main(String args[]) {
int n1 = 0, n2 = 1, n3, i, series_count = 9;
System.out.print("Fibonacci Series For First " + series_count + " numbers is: \n");
System.out.print(n1 + " " + n2);
for (i = 2; i < series_count; ++i) {
n3 = n1 + n2;
System.out.print(" " + n3);
n1 = n2;
n2 = n3;
}
}
}
Output :
Fibonacci Series For First 9 numbers is:
0 1 1 2 3 5 8 13 21