Java program to print N Fibonacci numbers using recursion

Fibonacci sequence or Fibonacci series are numbers in the sequence

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,...

The first two numbers in the sequence are 0 and 1. The subsequent number are obtained by adding the previous two number. Thus,
3rd number is 0 + 1 = 1
4th number is 1 + 1 = 2
5th number is 2 + 1 = 3

To programmatically print the Nth Fibonacci number you can either use nested loop or use recursion. Here is a program that prints the first N Fibonacci numbers using recursive method. The user inputs the number of Fibonacci numbers to be printed. You then use a for loop to loop until that limit each iteration will call the function fibonacci(int num) which returns the Fibonacci number at position num. The Fibonacci function recursively calls itself adding the previous two Fibonacci numbers.

import java.util.Scanner;

public class fibonacci {
    public static void main(String[] args) {
        
        Scanner keyboard = new Scanner(System.in);
        int limit;
        System.out.println("Enter how many Fibonacci number to print");
        limit = keyboard.nextInt();
        
        System.out.println("The first " + limit + "Fibonacci numbers are:");
        for (int i=0; i < limit; i++){
            System.out.println(fibonacci(i));
        }   
    }
    
     public static int fibonacci(int num) {

        if (num == 0) {
            return 0;
        }
        else if(num == 1)
        {
            return 1;
        }
     
       return fibonacci(num-1) + fibonacci(num-2);
    }
}

Program Output


Enter how many Fibonacci number to print
10
The first 10Fibonacci numbers are:
0  1  1  2  3  5  8  13  21  34 

Post a comment

Name

Your Comment

Email (We dont publish it)

Comments

Nothing yet..be the first to share wisdom.