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

Java is a popular programming language that is used to develop a wide range of applications. If you are a...
  • Java
  • March 6, 2023
Java is a programming language and computing platform that is used to create various types of applications. It is used...
  • Java
  • March 6, 2023
In this post, you’ll learn how to download and install JUnit in Eclipse so that you can use in your...
  • Java
  • October 9, 2022