Fibonacci Series Program in Java using Iterative method

The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. In Java, there are multiple ways to generate the Fibonacci series, and one of the most efficient methods is the iterative approach.

In this tutorial, we will explore how to implement the Fibonacci series using the iterative method in Java. We will start with understanding the basic logic behind the iterative approach, followed by writing a Java program that generates the Fibonacci sequence up to a specified number of terms.

For example, If user enters nth term as 5, then output should be 0 1 1 2 3.

Required Knowledge

What is Fibonacci Series?

The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. That is, the sequence starts 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on.

In mathematical terms, the Fibonacci sequence is defined by the recurrence relation:

F(n) = F(n−1)+F(n−2)

with initial conditions:

F(0)=0, F(1)=1

This series has many applications and appears in various aspects of mathematics, art, engineering, and nature. For example, the branching of trees, the arrangement of leaves on a stem, the fruitlets of a pineapple, the flowering of an artichoke, and the spirals of shells all exhibit Fibonacci patterns. The sequence is also closely associated with the golden ratio.

Problem Statement

We have to write a Java program to print Fibonacci series of a given number using iterative method. The program should take nth term (last number) and first two numbers are 0 and 1 ( default condition). Then using base condition we should find the Fibonacci series until the nth number. Let’s see an example,

Example

For input integer 4, output should be 0 1 1 2.

Explanation:

Input last integer number n = 4 

first num = 0

second num = 1 ( first two numbers are default values), iteration starts from 3 as first two numbers already there.

First Iteration(i=3): third num = first num+ second num = 0+1 =1

first num = second num =1, second num = third num = 1 (first num=1, second num=1)

Second Iteration (i=4): third num = first num + second num = 1+1 =2

Now first num = second num = 1, second num = third num = 2 (first num=1, second num=2)

After 2nd iteration with i=4, loop will end and prints the output as 0 1 1 2 ( Here 0 and 1, first two values are fixed by the user and it might be any other values other than 0 and 1)

Hence, For the n value 4, we will get the series as 0 1 1 2.

Logic to print Fibonacci series

  • Take the nth term (n) from the user. Using an if-else statement, check if n is less than or equal to 0. If true, print a message asking the user to enter a positive integer greater than 0.
  • Initialize firstNum to 0 and secondNum to 1, as these are the first two numbers in the Fibonacci sequence.
  • Using another if-else statement, check if n is 1. If true, directly print firstNum (which is 0). Otherwise, if n is greater than 1, print firstNum and secondNum.
  • Use a loop (while or for loop) to generate the Fibonacci series up to n terms:
    • Inside the loop, calculate thirdNum as the sum of firstNum and secondNum, and print thirdNum.
    • Update firstNum to secondNum and secondNum to thirdNum for the next iteration.
    • Increment the loop counter i.
  • Continue this until i reaches n.
  • Print each Fibonacci number separated by tabs (\t).

Java program to print Fibonacci Series

Program 1: Using while loop

In the below program we are using while loop to print Fibonacci series.

import java.util.Scanner;
public class FibonacciSeries {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
        System.out.println("Enter the number of terms for the Fibonacci Series: ");
        int n = s.nextInt();

        if (n <= 0) {
            System.out.println("Please enter a positive integer greater than 0.");
        } else {
            int firstNum = 0;
            int secondNum = 1;
            System.out.println("Fibonacci Series are:");
            if (n == 1) {
                System.out.println(firstNum); 
            } else {
                System.out.print(firstNum + "\t" + secondNum); 

                int thirdNum;
                int i = 3;
                while (i <= n) {
                    thirdNum = firstNum + secondNum;
                    System.out.print("\t" + thirdNum);
                    firstNum = secondNum;
                    secondNum = thirdNum;
                    i++;
                }
                System.out.println(); 
            }
        }
        s.close();
	}
}

Output:

Enter the number of terms for the Fibonacci Series:
5
Fibonacci Series are:
0 1 1 2 3

Java program explanation to print Fibonacci series

  • Input Handling: The program starts by creating a Scanner object to read user input. It then prompts the user to enter the number of terms they want in the Fibonacci series.
  • Input Validation: It checks if the entered number (n) is less than or equal to zero. If it is, the program prompts the user to enter a positive integer.
  • Fibonacci Calculation:
    • If n is 1, the program prints 0, the first number of the Fibonacci series.
    • If n is greater than 1, the program prints the first two numbers (0 and 1) and then computes the rest of the series up to the nth term using a loop. It achieves this by summing the last two numbers of the series to generate the next number.
  • Loop and Print: The program uses a while loop to calculate each subsequent term of the Fibonacci series from the third term onwards. Each new term is printed immediately.
  • Cleanup: Finally, the program closes the Scanner object to free up resources.

Program 2: Using for loop

In the below program we are using for loop to print Fibonacci series.

import java.util.Scanner;

public class FibonacciSeries {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.println("Enter the number of terms for the Fibonacci Series: ");
        int n = s.nextInt();

        if (n <= 0) {
            System.out.println("Please enter a positive integer greater than 0.");
        } else {
            int firstNum = 0;
            int secondNum = (n > 1) ? 1 : 0; 
            System.out.println("Fibonacci Series are:");
            System.out.print(firstNum);
            if (n > 1) {
                System.out.print("\t" + secondNum);
            }

            int thirdNum;
            for (int i = 3; i <= n; i++) {
                thirdNum = firstNum + secondNum;
                System.out.print("\t" + thirdNum);
                firstNum = secondNum;
                secondNum = thirdNum;
            }
            System.out.println();  
        }
        s.close();
    }
}

Output:

Enter the number of terms for the Fibonacci Series
6
Fibonacci Series are:
0 1 1 2 3 5

Java program explanation to print Fibonacci series

  1. User Input: The program uses a Scanner object to take an integer input from the user, specifying the number of terms (n) they wish to see in the Fibonacci series.
  2. Input Validation: It checks if the input value n is less than or equal to zero. If true, it prompts the user to enter a positive integer greater than 0, ensuring the program only processes valid input.
  3. Initial Sequence Setup: Depending on the value of n, the program initializes the first two numbers of the Fibonacci sequence. If n is 1, only 0 is initialized. If n is greater than 1, it initializes with 0 and 1.
  4. Fibonacci Calculation:
    • The program prints the first number directly.
    • If n is greater than 1, it prints the second number.
    • It then enters a loop starting from the third term (if n is 3 or greater) and calculates each subsequent Fibonacci number by adding the two preceding numbers.
  5. Output: Each calculated Fibonacci number is printed out, separated by tabs for clarity.
  6. Resource Management: The Scanner object is closed after its use to free up system resources.

Conclusion

In this article, we have learnt Fibonacci series using Iterative method in Java. We have seen the logic and implemented the program using while loop and for loop in Java. Hope this article helped you in the understanding of the program.

You can also check our another awesome tutorials:

  1. Armstrong number in Java
  2. Check perfect number in Java
  3. Java program to print all even numbers in a range in Java
  4. Java program to print all lowercase alphabets in Java

Happy Programming!!

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.