Java program for Fibonacci Series

Upasana | August 23, 2022 | 1 min read | 1,015 views


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

Fibonacci Series
fn = fn-1 + fn-2.

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.

Fibonacci using Iteration
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.

Tail recursion

A tail recursion is a recursive function where the function calls itself at the end ("tail") of the function in which no computation is done after the return of recursive call.

fibonacci series using Recursion
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:
  1. Java Coding Problems for SDET Automation Engineer
  2. 50 Java Interview Questions for SDET Automation Engineer
  3. Junit interview questions for SDET automation engineer
  4. Rest Assured API Testing Interview Questions
  5. Anagrams string checker in Java
  6. Java Program to find Factorial of a number
  7. Essential Java Skills for SDET Automation Engineer

Recommended books for interview preparation:

Find more on this topic: