Java Tutorial

# Java Program for Fibonacci Series

## Fibonacci Series Algorithm

Fibonacci series is an integer sequence where every number after the first two is the sum of the two preceding ones.

Fibonacci n'th term is calculated as sum of n-1'th term and n-2'th term.

```F{n}=F{n-1}+F{n-2}
where F{0} = 0 and F{1} = 1
```

## Java Program to Generate Fibonacci Series using while loop

Reads the number of terms as user input and calculates and displays the fibonacci series numbers.

```import java.util.*;

class FibonacciSeries
{
public static void main(String args[]) {
System.out.println("Fibonacci series");
Scanner Sc=new Scanner(System.in);
System.out.println("Enter the number of terms: ");
int  num=Sc.nextInt();
int a=0;
int b=1;
System.out.println("Fibonacci series");
System.out.println("---------------------");
System.out.print(a+"\t");
System.out.print(b+"\t");
int i=2;
while(i<num) {
int c=a+b;
System.out.print(c+"\t");
a=b;
b=c;
i++;
}
}
}
```
Output:
```D:\Java_Programs>javac FibonacciSeries.java
D:\Java_Programs>java FibonacciSeries
Enter the number of terms:
6
Fibonacci series
---------------------
0	1	1	2	3	5

D:\Java_Programs>javac FibonacciSeries.java
D:\Java_Programs>java FibonacciSeries
Enter the number of terms:
10
Fibonacci series
---------------------
0	1	1	2	3	5	8	13	21	34
```

## Java Program to Generate Fibonacci Series using for loop

```import java.util.*;

class FibonacciSeries
{
public static void main(String args[]) {
Scanner Sc=new Scanner(System.in);
System.out.println("Enter the number of terms: ");
int  num=Sc.nextInt();
int a=0;
int b=1;
System.out.println("Fibonacci series");
System.out.println("---------------------");
System.out.print(a+"\t");
System.out.print(b+"\t");
for(int i=2;i<num;i++) {
int c=a+b;
System.out.print(c+"\t");
a=b;
b=c;
}
}
}
```
Output:
```D:\Java_Programs>javac FibonacciSeries.java
D:\Java_Programs>java FibonacciSeries
Enter the number of terms:
6
Fibonacci series
---------------------
0	1	1	2	3	5

D:\Java_Programs>javac FibonacciSeries.java
D:\Java_Programs>java FibonacciSeries
Enter the number of terms:
10
Fibonacci series
---------------------
0	1	1	2	3	5	8	13	21	34
```

Java Tutorial