fn = fn-1 + fn-2.

# Calculate Fibonacci Series in Java

Carvia Tech | April 30, 2019 | 1 min read | 33 views

Fibonacci series is series of natural number where next number is equivalent to the sum of previous two number e.g.

The first two numbers of Fibonacci series is always 1, 1.

First 10 numbers in fibonacci series are:

1 1 2 3 5 8 13 21 34 55

## Iterative approach

Java program to calculate and print Fibonacci number using Iterations logic is shown below:

Basically on each iteration, we are assigning second number to the first and assigning the sum of last two numbers to the second.

```
void fibonacci(int count) {
int prevNumber = 0;
int nextNumber = 1;
System.out.println("Fibonacci Series " + count + ":");
for (int i = 1; i <= count; ++i) {
int fib = prevNumber + nextNumber;
prevNumber = nextNumber;
nextNumber = fib;
System.out.print(prevNumber + " ");
}
}
```

## Recursive approach

We can use *tail recursion* to calculate fibonacci series in Java.

```
int fibonacci(int num) {
if (num == 1 || num == 2) {
return 1;
```**(1)**
}
return fibonacci(num - 1) + fibonacci(num - 2); **(2)**
}

1 |
Terminating condition for recursive function |

2 |
Tail recursion where we are essentially calculating `fn = fn-1 + fn-2` |

###### Top articles in this category:

- Top 50 SDET Java Programming Interview Questions & Answers
- Calculate factorial of a number in Java using recursion
- Commonly used Http methods in RESTful services
- Check if the given number is Armstrong Number in Java
- Write a program to reverse a string using recursion in Java
- What is difference between Enumeration and Iterator in Java
- Find longest non-repeating substring from a given string in Java

###### Find more on this topic:

##### SDET Interviews

End to end automation testing using Selenium Web Driver, Rest Assured, JMeter, Junit, TestNG etc.

Last updated 1 month ago

###### Recommended books for interview preparation:

##### Facebook Page

##### Similar Posts

- File upload in RestAssured
- Basic Authentication using RestAssured
- What is difference between Enumeration and Iterator in Java
- Creating custom exceptions in Java
- Find two numbers of which the product is maximum in an array
- Write a program to reverse the order of words in a string
- Check whether given number is even or odd
- Check a number is Prime: Java Coding Problem
- Create anagram buckets from a given input array of words
- Java program to check if two strings are anagrams

Enter your email address to subscribe to this blog and receive notifications of new posts by email.