Fibonacci Series Program in Java

Fibonacci series is a series whose every term is comprised of adding its previous two terms, barring the first two terms 0 and 1. Thus, we will get the series as 0, 1, 1, 2, 3, 5, 8, ……

We get the third term as 1 because its previous two terms are 0 and 1. The fourth term is 2 because its previous two terms are 1 and 1 and so on. Again, we will be discussing both the iterative as well as the recursive approach. Let us start with the iterative one.

Iterative Approach

Filename: FibonacciExample.java

public class FibonacciExample

{

public static void main(String[] args)

{

// a and b will always contain the last two terms

// c will always contain the next term

int a = 0, b = 1, c;

int n = 6; //We are calculating the series till the 6th term.

System.out.println(“The first “ + n + “ terms of the Fibonacci series are:”);

for(int j = 0; j < n; j++)

{

if (j == 0)

System.out.print(a + “ “);

else if( j == 1)

System.out.print(b + “ “);

else

{

//calculating next term

c = a + b;

System.out.print(c + “ “);

//Updating the last two terms

a = b;

b = c;

}

}

}

}