# Fibonacci Series in Java

Hello and Welcome to **The World of Computer Science and Technology**

**www.TechWithCode.com**

Today we will learn about how to write a **Java Program to find the Fibonacci Series**. Before moving forward, we must have knowledge about **what Fibonacci Series is**?

## What is Fibonacci Series?

A series of numbers in which each number ( Fibonacci number ) is the sum of the two preceding numbers. The simplest is the series 0,1, 1, 2, 3, 5, 8, etc.

## Ways to Calculate Fibonacci Series in Java

There can be many ways in programming to find the factorial of any number but today we will discuss two important way with the source code

- Fibonacci Series Program using loop
- Fibonacci Series Program using recursion
- Display Fibonacci series up to a given number

## 1. Fibonacci Series Program using loop

#### Problem Statement⤵️

Write a Java program to find the Fibonacci Series using the loop.

#### Source code⤵️

```
class Fibonacci{
public static void main(String args[])
{
int n1=0,n2=1,n3,i,count=10;
System.out.print("First " + count + " terms of Fibonacci Series: ");
System.out.print(n1+" "+n2);//printing 0 and 1
for(i=2;i<count;++i)//loop starts from 2 because 0 and 1 are already printed
{
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}
}}
```

#### Source code⤵️

```
First 10 terms of Fibonacci Series:0 1 1 2 3 5 8 13 21 34
```

## 2. Fibonacci Series Program using recursion

#### Problem Statement⤵️

Write a Java program to find the Fibonacci Series using the recursion.

#### Source code⤵️

```
class Fibonacci{
static int n1=0,n2=1,n3=0;
static void printFibonacci(int count){
if(count>0){
n3 = n1 + n2;
n1 = n2;
n2 = n3;
System.out.print(" "+n3);
printFibonacci(count-1);
}
}
public static void main(String args[]){
int count=10;
System.out.print("First " + count + " terms of Fibonacci Series: ");
System.out.print(n1+" "+n2);//printing 0 and 1
printFibonacci(count-2);//n-2 because 2 numbers are already printed
}
}
```

#### Source code⤵️

```
First 10 terms of Fibonacci Series:0 1 1 2 3 5 8 13 21 34
```

## 3. Display Fibonacci series up to a given number

#### Problem Statement⤵️

Write a Java program to find the Fibonacci series up to a given number.

#### Source code⤵️

```
public class FibonacciUptoN {
public static void main(String[] args) {
int count = 100, t1 = 0, t2 = 1;
System.out.print("Fibonacci Series upto " + count + ": ");
while (t1 <= count)
{
System.out.print(t1 + " , ");
int sum = t1 + t2;
t1 = t2;
t2 = sum;
}
}
}
```

#### Source code⤵️

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

## No comments:

Do not add any link in the comments.

For backlink, contact us.