fibonacci series in java

Today, We want to share with you fibonacci series in java.In this post we will show you Fibonacci Series generates subsequent number by including two previous numbers., hear for display fibonacci series in Java using for and while loops. we will give you demo and example for implement.In this post, we will learn about GO Program To Display Fibonacci Sequence with an example.

Java Program to Display Fibonacci Series

each number is the sum of the two previous numbers. The first two numbers in the Fibonacci series are 0 and 1. Fibonacci series satisfies the following conditions −

Fn = Fn-1 + Fn-2

The beginning of the sequence is thus:

Read Also:  How to Insert Data in Database using PHP OOPS

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

Algorithm

1. Take integer variable A, B, C
2. Set A = 1, B = 1
3. DISPLAY A, B
4. C = A + B
5. DISPLAY C
6. Set A = B, B = C
7. REPEAT from 4 - 6, for n times

Display Fibonacci series using for loop

Example 1:

public class ExampleOfFiboDemo {

    public static void main(String[] args) {

        int n = 10, firstVal = 0, secondVal = 1;
        System.out.print("First " + n + " series: ");

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

            int sum = firstVal + secondVal;
            firstVal = secondVal;
            secondVal = sum;
        }
    }
}

Output

0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 + 

Display Fibonacci series using while loop

Example 2:

public class ExampleOfFiboDemo {

    public static void main(String[] args) {

        int i = 1, n = 10, firstVal = 0, secondVal = 1;
        System.out.print("First " + n + " series: ");

        while (i <= n)
        {
            System.out.print(firstVal + " + ");

            int sum = firstVal + secondVal;
            firstVal = secondVal;
            secondVal = sum;

            i++;
        }
    }
}

Display Fibonacci series up to a given number (instead of series)

Example 3:

public class ExampleOfFiboDemo {

    public static void main(String[] args) {

        int n = 100, firstVal = 0, secondVal = 1;
        
        System.out.print("Upto " + n + ": ");
        while (firstVal <= n)
        {
            System.out.print(firstVal + " + ");

            int sum = firstVal + secondVal;
            firstVal = secondVal;
            secondVal = sum;
        }
    }
}

Output

Upto 100: 0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 + 55 + 89 + 

I hope you get an idea about fibonacci series in java.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.