Before looking at the fibonacci series program in Java, let’s explore what is the mathematical way of calculating fibonacci numbers.
“Fibonacci series is formed when we add up the last two consecutive numbers of the sequence beginning with 0 and 1.”
In other words we can say, in a fibonacci sequence the next number is equal to the sum of the last two numbers.
For example, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34…
If we look at the above series, it looks pretty simple to calculate in mathematics. You just take the last two fibonacci numbers, add them and there you are. The result is the latest number in the series.
So the next number in the fibonacci sequence will be 21 + 34 = 55.
However, in Java there are various algorithms to do that. Let’s have a look at our possible ways.
Fibonacci Series in Java [ Iterative Method ]
Our first and most basic way to calculate a fibonacci series program in Java will be using an iterative method. As the name suggests, we will iterate the series using a loop. Let’s dig deeper in the following example.Example
public class IterativeFibonacci {
public static void fibonacci(int MAX) {
int firstNumber = 0;
int secondNumber = 1;
int fibonacci = '\0';
System.out.print(firstNumber + " ");
System.out.print(secondNumber + " ");
for (int i = 2; i < MAX; i++) {
fibonacci = firstNumber + secondNumber;
System.out.print(fibonacci + " ");
firstNumber = secondNumber;
secondNumber = fibonacci;
}
}
public static void main(String[] args) {
System.out.println("Print Fibonacci Series Using Iterative Method");
int MAX = 15;
fibonacci(MAX);
}
}
Output
Print Fibonacci Series Using Iterative Method
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
Explanation
In the above example, we are using a method called “fibonacci” to print the fibonacci series iteratively. The variable MAX stores the total number of fibonacci numbers you want to print. The two variables firstNumber and secondNumber store the first two fibonacci numbers respectively. Then the for loop begins with i = 2, because first and second fibonacci numbers are already printed. In each iteration, the first and the second number are updated to keep the series going. The loop ends, as it approaches the MAX limit i-e; i < MAX.Fibonacci Series Using Recursion in Java
Since you’re familiar with the iterative method, let’s compute fibonacci series using recursion in Java.Example
public class RecursiveFibonacci {
// recursive method to return the fibonacci series
public static int fibonacci(int MAX) {
// base case
if (MAX <= 1) {
return MAX;
}
// recursive call
else {
// calculate the last two fibonacci numbers recursively
return fibonacci(MAX - 2) + fibonacci(MAX - 1);
}
}
public static void main(String[] args) {
System.out.println("Print Fibonacci Series Using Recursion in Java");
int MAX = 10;
for (int i = 0; i < MAX; i++) {
System.out.print(fibonacci(i) + " ");
}
}
}
Output
Print Fibonacci Series Using Recursion in Java
0 1 1 2 3 5 8 13 21 34
GO TO FULL VERSION