Java Practice Program: Fibonacci Sequence

Write a Java program to generate the Fibonacci Sequence up to a specified number of terms

Fibonacci Sequence

What is the Fibonacci Sequence?
The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, starting from 0 and 1.
For example:
0, 1, 1, 2, 3, 5, 8, …

class Main {
    public static void main(String[] args) {
        int first = 0, second = 1, next = 0;
        
        // Print the first Fibonacci number (0)
        System.out.print(first + " ");
        
        // Print the second Fibonacci number (1)
        System.out.print(second + " ");
        
        // Start calculating and printing the next Fibonacci numbers
        for (int i = 1; i <= 5; i++) {
            next = first + second;
            first = second;
            second = next;
            System.out.print(next + " ");
        }
    }
}

Initialization:

first and second represent the first two numbers in the Fibonacci sequence (0 and 1).
next will store the next number in the sequence.

Printing the first two numbers:
System.out.print(first + ” “); prints 0.
System.out.print(second + ” “); prints 1.

Step-by-step process for each iteration:
Calculate the next Fibonacci number:
next = first + second;
(Sum of the previous two numbers.)

Update the first and second variables:
first = second;
second = next;

This shifts the sequence forward for the next calculation.
Print the next number:
System.out.print(next + ” “);

Output

When the program is executed, the output will be:

0 1 1 2 3 5 8

Breakdown of Output
First two numbers: 0, 1 (printed outside the loop).
Loop calculations:
Iteration 1: 0 + 1 = 1
Iteration 2: 1 + 1 = 2
Iteration 3: 1 + 2 = 3
Iteration 4: 2 + 3 = 5
Iteration 5: 3 + 5 = 8

Leave a Reply