Create Fibonacci Series using Java

thumbnail

Today, we will learn to create fibonacci series in Java using for and while loops. Then, you will learn to display the series upto a specific term or a number. If you dont know about Fobonacci Series, Here is the short explanation about it.
The Fibonacci Series is a series where the next term is the sum of previous two terms. The first two terms of the Fibonacci sequence is 0 followed by 1. The sequence will be showed like below:

0, 1, 1, 2, 3, 5, 8, 13, 21, ...

There will be two example that will show in this tutorial.

Example 1: Generate Fibonacci series using for loop in Java

public class Fibonacci {
    public static void main(String[] args) {
        int n = 10, t1 = 0, t2 = 1;
        for (int i = 1; i <= n; ++i)
        {
            System.out.println(t1);
            int sum = t1 + t2;
            t1 = t2;
            t2 = sum;
        }
    }
}

The output will be:

0
1
1
2
3
5
8
13
21
34

Example 2: Generate Fibonacci series using while loop in Java

public class Fibonacci {
    public static void main(String[] args) {
        int i = 1, n = 10, t1 = 0, t2 = 1;
        while (i <= n)
        {
            System.out.println(t1);
            int sum = t1 + t2;
            t1 = t2;
            t2 = sum;
            i++;
        }
    }
}

The output will be:

0
1
1
2
3
5
8
13
21
34
Back To Top