Before we begin to see the code to create the Fibonacci series program in Java using recursion or without it, let's understand what does Fibonacci means.
Fibonacci series is a series of natural numbers where next number is equivalent to the sum of previous two numbers i.e. fn = fn-1 + fn-2.In fibonacci sequence each item is the sum of the previous two. So, you wrote a recursive algorithm, for example, recursive function example for up to 5
fibonacci(5) = fibonacci(4) + fibonacci(3)
fibonacci(3) = fibonacci(2) + fibonacci(1)
fibonacci(4) = fibonacci(3) + fibonacci(2)
fibonacci(2) = fibonacci(1) + fibonacci(0)
The first two numbers in the Fibonacci sequence are either 1 and 1, or 0 and 1, and each subsequent number is the sum of the previous two numbers.
Fibonacci series recursion program in Java
package com.fib;
import java.util.Scanner;
public class fibonacciExample {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number to limit Fibonacci series: ");
int num = input.nextInt();
//loop till the last count
for(int i = 1; i <= num; i++){
//call Fibonacci function to print sum of last two numbers
System.out.print(printFibonacci(i) + " ");
}
input.close();
}
// recursion function
private static int printFibonacci(int CurrentNumber){
//exit condition
if(CurrentNumber == 1 || CurrentNumber == 2){
return 1;
}
return printFibonacci(CurrentNumber - 1) + printFibonacci(CurrentNumber - 2);
}
}
Output:
Enter how many numbers are needed in Fibonacci series:
10
1 1 2 3 5 8 13 21 34 55
In the above code, at first, we are asking the user to enter the number of counts up to which user wants to print the series, using loop we pass the number to "printFibonacci" function and then add last two number using logic (num) + (number-1). Since the first two numbers in the series are 1, 1 so return 1 for both n equals 1 and 2 in the recursive method.
Fibonacci Series program in Java without Recursion
package com.fib;
import java.util.Scanner;
public class fibonacciExample {
public static void main(String[] args)
{
int i = 1, t1 = 0, t2 = 1;
Scanner input = new Scanner(System.in);
System.out.println("Enter the number to limit Fibonacci series: ");
int num = input.nextInt();
System.out.println("First " + num + " terms: ");
while (i <= num) {
System.out.print(t1 + " ");
int sum = t1 + t2;
t1 = t2;
t2 = sum;
i++;
}
input.close();
}
}
Output:
Enter the number to limit Fibonacci series:
10
First 10 terms:
0 1 1 2 3 5 8 13 21 34
You may also like:
Pyramid Triangle pattern programs in Java with explanation
Java program to reverse a string (Different ways explained)
Leap year program in Java (multiple ways)
Program to remove duplicate elements in an array in Java
Declare and initialize Array in java
7 Ways to Merge or Split PDF Files in Java
Fibonacci series In C# (Various possible ways)