fibonacci series in java using loop – Clear Logic

The Fibonacci series is a sequence of numbers in which each number after the first two is the sum of the two preceding ones.

It is defined as follows:

F(0) = 0 F(1) = 1 F(n) = F(n-1) + F(n-2) for n > 1

So, the first few terms of the Fibonacci series are:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, …

To implement this logic in Java, we can use a loop to calculate the Fibonacci numbers one by one.

Here is an example code and explanation:

public class FibonacciSeries {
    public static void main(String[] args) {

        int n = 10; // number of terms to generate

        int first = 0, second = 1;

        System.out.print("Fibonacci Series of "+n+" terms:");

        for (int i = 1; i <= n; ++i) {
            System.out.print(first + " ");

            // compute the next term in the series
            int sum = first + second;
            first = second;
            second = sum;
        }
    }
}

In this code, we first define the number of terms to generate as n. We then initialize the first two terms of the series as 0 and 1.

We use a loop to generate the next n-2 terms of the series. Inside the loop, we first print the current term (first) and then compute the next term by adding the previous two terms (first and second).

Finally, we update first and second to prepare for the next iteration of the loop.

When we run this code, it will generate the first 10 terms of the Fibonacci series:

Fibonacci Series of 10 terms:0 1 1 2 3 5 8 13 21 34

Related Posts