Home / Programs / Displaying Fibonacci Sequence using while loop
Programming Example

Displaying Fibonacci Sequence using while loop

👁 1,277 Views
💻 Practical Program
📘 Step by Step Learning
Displaying Fibonacci Sequence using while loop:

Program Code

public class JavaExample {

    public static void main(String[] args) {

        int count = 7, num1 = 0, num2 = 1;
        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

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

Explanation

None

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.