Display Fibonacci Series in Java

Exercise:

Write a Java Program that displays Fibonacci numbers.

1.Display Fibonacci series using while loop

Click Here to View the Solution!
public class FibonacciSeries {
  
     public static void main(String[] args) {
  
         int n = 50, n1 = 0, n2 = 1;
         
         System.out.print("Upto " + n + ": ");
         while (n1 <= n)
         {
             System.out.print(n1 + " + ");
  
             int sum = n1 + n2;
             n1 = n2;
             n2 = sum;
         }
     } 
}
Click Here to View the Output!
Upto 50: 0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 + 
Click Here to View the Explanation!
  • This program is used for displaying the Fibonacci series by using the for loop.
  • Initially, three integer variables n, n1 and n2 are initialized as n = 50, n1 = 0 and n2 = 1. Where n is the number of times the iteration will occur in the for loop, n1 and n2 are initialized as the first two values of the Fibonacci series (n1=0 and n1=1).
  • Another integer variable sum is initialized that will hold the sum of n1 and n2. The variable sum will hold the sum of the previous two values which will be held by the variable n1. The values are then substituted as n1 = n2 because the values have to increment according to the sum after each iteration. And then finally, the sum will be substituted for n2. Now, both n1,n2 will be equal to 1 (0+1=1).
  • In the end, the Fibonacci series are displayed with a + operator between each number.

2.Display up-to a given number

Click Here to View the Solution!
public class FibonacciSeries {
 
    public static void main(String[] args) {
 
        int n = 70, n1 = 0, n2 = 1;
        
        System.out.print("Upto " + n + ": ");
        while (n1 <= n)
        {
            System.out.print(n1 + " + ");
 
            int sum = n1 + n2;
            n1 = n2;
            n2 = sum;
        }
    }
} 
Click Here to View the Output!
Upto 70: 0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 + 55 + 
Click Here to View the Explanation!
  • This program is used for displaying the Fibonacci series till a specified number rather than terms.
  • Considering the previous programs, that displayed the Fibonacci series for a specified number, this program will display the series till a given number n = 70.
  • Both n1 and n2 are initialized as 0 and 1 and a while loop is given the condition that keep on iterating till the sum of the previous two numbers is less than or equal to n.
  • Since n1 will hold the sum, the displaying of the Fibonacci series will continue till n1 remains smaller or equal to n1. Else, the iteration will stop.
  • As a result, the entire Fibonacci series will be printed up to 70.

%d bloggers like this: