# Fibonacci series program in Java ## What is the Fibonacci series?

A Fibonacci series is a set of numbers where, starting with the third number, each number is the sum of the two numbers before it. To put it another way, every number in the series is the product of the two numbers that came before it. The numbers 0 and 1 are frequently the first two in the Fibonacci series.

An example of a Fibonacci series is given below:

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

``````

## Fibonacci series program in Java

In Java, the Fibonacci series is a sequence of numbers in which every third number is equal to the sum of the previous two numbers. The first two integers in the Fibonacci series are 0 and 1.

import java.util.Scanner;

```public class Fibonacci
{
public static void main(String args[])
{
int n, i, first = 0, second = 1, next;

System.out.println("Enter the number of terms");
Scanner enter = new Scanner(System.in);
n = enter.nextInt();

System.out.println("Fibonacci series are");
for (i = 0 ; i < n ; i++)
{
if (i <= 1)
next = i;
else
{
next = first + second;
first = second;
second = next;
}
System.out.println(next);
}

}
}
```

Output

Print the Fibonacci Series up to the N term for a specified input integer N.

```Enter the number of terms
5
Fibonacci series are
0
1
1
2
3
```

## Fibonacci Series in Java using For Loop

This loop is similar to the while loop. After initializing the first two digits, we print the first term of the sequence, thus calculating the next term using the Fibonacci formula.

Finally, proceed by assigning the first term the value of the second term and the second term the value of the next term.

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

int n = 13, t1 = 0, t2 = 1;
System.out.println("Fibonacci Series of " + n + " terms:");

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

// compute the next term
int sum = t1 + t2;
t1 = t2;
t2 = sum;
}
}
}
```

Output

```Fibonacci Series of 13 terms:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144,
```

In the preceding code, firstTerm(t1) and secondTerm(t2) are set to 0 and 1, respectively. (The first two points of the Fibonacci series). In this case, we used a for loop to print t1 of the series, calculate the sum by adding t1 and t2 and assign t2 the value of t1 and the sum of t2.

Time Complexity: -O(N)

## conclusion

We have covered four approaches in this article. The Fibonacci series is a numerical sequence in which each number (except the first two) is the sum of the two numbers preceding it. We can generate a Fibonacci sequence recursively or recursively. We can use the memoization method to speed up the computation of the Fibonacci series program.

Good luck and happy learning!