Java Program to Print Fibonacci Series Using Loops

In this post, you will learn How to Print Fibonacci Series Using loops in Java Programming language.

java-fibonacci-series

Before getting straight into Java Program to Print Fibonacci Series using Loops. Let’s see “What is a Fibonacci Series ?”

A Fibonacci sequence is a sequence in which the next term is the sum of the previous two terms.
The series will go like :
0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , . . . . . . and so on.

Java Program to Print Fibonacci Series Using Loops

import java.util.*;

public class Main{

    public static void main(String[] arg){
        
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int nextValue = 0;
        int first = 0;
        int second = 1;
        System.out.print("0, 1, ");
        for(int i=3; i<=n ;i++){
           
            nextValue = first+second;
            first = second;
            second = nextValue;
            System.out.print(""+nextValue+", ");
        }
        
    }
    
}

Output

Enter the number of terms: 12
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,

How Does This Program Work ?

In the above program, the first and second are initialized with 0 and 1 respectively which is the 1st to a term of the Fibonacci series.
we have used the for loop to compute the next value by adding first and second. Then first value becomes the second value and the second value becomes the next value.

for(int i=3; i<=n ; i++ ){
      nextValue = first+second;
      first = second;
      second = nextValue;
      System.out.print(""+nextValue+", ");
}

Learn more: Java Program to Print Fibonacci Series Using Recursion

Conclusion

I hope after going through this post, you understand how to code Java Program to Print Fibonacci Series using loops.
If you have any doubt regarding the topic, feel free to contact us in the Comment Section. We will be delighted to help you.

Also Read:

Leave a Comment

Your email address will not be published.