February 1, 2022

Fibonacci Series Java Program

In this post we’ll see a Java program to display Fibonacci series.

Fibonacci series is a series of natural number where next number is the sum of previous two numbers i.e. fn = fn-1 + fn-2. For example

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

Java program for displaying Fibonacci series can be written using-

  1. Recursive logic. See example.
  2. Non-recursive logic. See example.

Fibonacci series program using recursion logic

import java.util.Scanner;

public class FibonacciSeries {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    //user input
    System.out.println("Enter length of the Fibonacci series: ");
    int num = sc.nextInt();
    for(int i = 0; i < num; i++){
      System.out.print(displayFibonacci(i) + " ");
    }
  }
	
  private static int displayFibonacci(int num){
    if(num == 0){
      return 0;
    }
    if(num == 1){
      return 1;
    }
    // sum of previous two numbers - calling recursively
    return displayFibonacci(num - 1) + displayFibonacci(num - 2);
  }
}
Output
Enter length of the Fibonacci series: 
10
0 1 1 2 3 5 8 13 21 34 

Fibonacci series Java program using iteration

import java.util.Scanner;

public class FibonacciSeries {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    //user input
    System.out.println("Enter length of the Fibonacci series: ");
    int num = sc.nextInt();

    displayFibonacci(num);
  }
	
  private static void displayFibonacci(int num){
    int num1 = 0;
    int num2 = 1;
    int num3 = 0;
    for(int i = 0; i <num; i++){
      System.out.print(num3+" ");
      num1 = num2;
      num2 = num3;
      num3 = num1 + num2;
    }
  }
}
Output
Enter length of the Fibonacci series: 
15
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 

That's all for the topic Fibonacci Series Java Program. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment