Java Program to Display Fibonacci Sequence

In this java program, you’ll learn how to Display Fibonacci Sequence using the JAVA programming language

Here, 0 and 1 are the first two terms of Fibonacci series. The next number is the sum of the previous two number. 

How to Display Fibonacci Sequence using Java Program? 

Example 1: using while loop 

RUN CODE SNIPPET
class Main { 
  public static void main(String[] args) { 
    int i = 1, n = 20, firstTerm = 0, secondTerm = 1; 
    System.out.println("Fibonacci Series till " + n + " terms:"); 
    while (i <= n) { 
      System.out.print(firstTerm + ", "); 
      int nextTerm = firstTerm + secondTerm; 
      firstTerm = secondTerm; 
      secondTerm = nextTerm; 
      i++; 
    } 
  } 
}

OUTPUT 

Fibonacci Series till 20 terms:  0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181,

Example 2: using for loop 

RUN CODE SNIPPET
public class Main { 
    public static void main(String[] args) { 
        int count = 5, num1 = 0, num2 = 1; 
        System.out.print("Fibonacci Series of "+count+" numbers:"); 
        for (int i = 1; i <= count; ++i) 
        { 
            System.out.print(num1+" "); 
            int sumOfPrevTwo = num1 + num2; 
            num1 = num2; 
            num2 = sumOfPrevTwo; 
        } 
    } 
}

OUTPUT 

Fibonacci Series of 5 numbers:0 1 1 2 3

Example 3: display the Fibonacci series based on the based on the user input 

import java.util.Scanner; 
public class Main { 
    public static void main(String[] args) { 
        int count, num1 = 0, num2 = 1; 
        System.out.println("How may numbers you want in the sequence:"); 
        Scanner scanner = new Scanner(System.in); 
        count = scanner.nextInt(); 
        scanner.close(); 
        System.out.print("Fibonacci Series of "+count+" numbers:"); 
        int i=1; 
        while(i<=count) 
        { 
            System.out.print(num1+" "); 
            int sumOfPrevTwo = num1 + num2; 
            num1 = num2; 
            num2 = sumOfPrevTwo; 
            i++; 
        } 
    } 
}

OUTPUT 

How may numbers you want in the sequence: 

Fibonacci Series of 7 numbers:0 1 1 2 3 5 8

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this Java program, we will learn how to find the GCD of two numbers using Java.  GCD (Greatest Common...
  • Java
  • December 3, 2024
In this Java Program, you’ll learn how to swap two numbers using the Java programming language.  How to Swap Two...
  • Java
  • December 2, 2024
In this Java program , we will learn how to Find Largest Element in an Array in your Java program.   How to Find Largest Element...
  • Java
  • December 2, 2024