VALUES

Fibonacci series using Java program

                     Hello friends, In this blog we see the how to generate Fibonacci series using java. In C, CPP and Python programs we see what is Fibonacci series. So Without giving the definition of Fibonacci series we see the program.

Program:
1. (Using for loop)
public class Fibonacci
{
    public static void main(String[] args)
{
        int a = 0, b = 1;
        System.out.println(“First 10 terms: “);
        for (int i = 1; i <= 10; ++i)
        {
            System.out.println(a + ”  “);
            int sum = a + b;
            a = b;
            b = sum;
        }
    }
}

           In  the above program we use two variables that is a and b and assign the value 0 and 1 respectively. For loop is used to initialize the value of ‘i’ variable and increment it by 1. And we put the condition that is the ‘i’ must be less than or equal to 10. So we see the output of 10 numbers only.

2. Using while loop

public class Fibonacci
{
    public static void main(String[] args)
{
        int i = 1, a = 0, b = 1;
        System.out.println(“First 10 terms: “);
        while(i<=10)
        {
            System.out.println(a + ”  “);
            int sum = a + b;
            a = b;
            b = sum;
            i++;
        }
    }
}

In the above code instead of for loop we use the while loop and incremented I variable in the middle loop. The output of both code is exactly same.
   
Output:



Related Articles

Back to top button