Fibonacci series is series of natural number where next number is equivalent to the sum of previous two numbers
i.e. **fn = fn-1 + fn-2**. The *first two numbers of Fibonacci series are always 1 and 1*.

Fibonacci series Java program can be written either using **recursive logic** or **iterative logic**. In this post we'll
see Java programs for both.

__Fibonacci using recursion__

If you are using recursive logic then you have to call the same method with both **n-1** and **n-2** where n
is the passed number. If you want Fibonacci series to have only one number then it would be 1, if you want two numbers
then it would be 1, 1. So n=1 and n=2 are the **base cases** for recursive program.

import java.util.Scanner; public class Fibonacci { public static void main(String[] args) { Scanner input = new Scanner(System.in); //user input System.out.println("Enter how many numbers are needed in Fibonacci series: "); int num = input.nextInt(); for(int i = 1; i <= num; i++){ System.out.print(printFibonacci(i) + " "); } input.close(); } private static int printFibonacci(int num){ //exit condition if(num == 1 || num == 2){ return 1; } return printFibonacci(num - 1) + printFibonacci(num - 2); } }

__Output__

Enter how many numbers are needed in Fibonacci series : 12 1 1 2 3 5 8 13 21 34 55 89 144

__Fibonacci using iteration__

In Fibonacci series next number is the sum of previous two numbers. Iterative program uses the same logic by taking three variables, in a for loop you first print the number and then move one step forward by assigning the previous two numbers to two of the variables and assigning the sum of these two variables to the third variable.

import java.util.Scanner; public class FibonacciItr { public static void main(String[] args) { Scanner input = new Scanner(System.in); //user input System.out.println("Enter how many numbers are needed in Fibonacci series: "); int num = input.nextInt(); printFibonacci(num); input.close(); } private static void printFibonacci(int num){ int num1, num2 = 0; int num3 = 1; for(int i = 1; i <=num;i++){ System.out.print(num3+" "); num1 = num2; num2 = num3; num3 = num1 + num2; } } }

__Output__

Enter how many numbers are needed in Fibonacci series: 14 1 1 2 3 5 8 13 21 34 55 89 144 233 377

That's all for this topic **Fibonacci series program in Java**. If you have any doubt or any
suggestions to make please drop a comment. Thanks!

__Related Topics__

**You may also like - **

## No comments:

## Post a Comment