Fibonacci Series in Java using with Recursion, Scanner, For & While Loop

Fibonacci Series in Java using with Recursion, Scanner, For & While Loop

10 Sep 2024
Beginner
844 Views
31 min read

Fibonacci Series in Java

Fibonacci Series in Java, It is the outcome of a series of numbers where the subsequent numbers build a relationship with the preceding numbers. This series will start from 0 to the numbers equal to the sum of the two numbers that are previously defined. When the Java Fibonacci series program is given an integer input of N, it produces a Fibonacci Series of N numbers.

This Java tutorial will assist you in learning about the Fibonacci series in Java, how to generate the series using a scanner, how to implement the series using recursion, how to implement the series using a for loop, how to implement the series using a while loop, how to implement the series using memoization, dynamic programming, iterative approach, and many other topics.

Fast-track your full stack development journey by enrolling in our Java Full Stack Developer Training now!

What is the Fibonacci Series?

Fibonacci Seriesis a sequence of numbers that start from 0 and 1; each increasing element is a result of adding the two preceding elements.The Fibonacci series looks like

The important point for the Fibonacci Series:

  • The first number is 0.
  • The second number is 1.
  • The following number is equal to the sum of the two numbers that came before it.
  • The Fibonacci sequence may be computed using the recursive formula F(n) = F(n-1) + F(n-2).
Read More:
Best Java Developer Roadmap 2024
Get to know Java Developer Salary Guide in India – For Freshers & Experienced
Understand Fibonacci Series in Python

How can we use a Scanner to generate the Fibonacci Series?

The Scanner class in Java may be used to produce the Fibonacci seriesby allowing the user to enter the number of words. We follow some steps to generate the Fibonacci Series in that are:

  • Step 1- we use to import thejava.util.Scanner class.
  • Step 2- we define an Scanner class object that read user input.
  • Step 3- Inquire as to how many Fibonacci series words the user wants to produce.
  • Step 4- We use a loop and the user's input to create and print the Fibonacci series.

Example

import java.util.Scanner;

public class FibonacciSeries {
    public static void main(String[] args) {
        // Create a Scanner object to read input
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the number of terms: ");
        int n = scanner.nextInt();

        // Variables to store the first two terms
        int firstTerm = 0, secondTerm = 1;

        System.out.println("Fibonacci Series of " + n + " terms:");

        // Loop to generate the Fibonacci series
        for (int i = 1; i <= n; ++i) {
            System.out.print(firstTerm + " ");

            // Compute the next term
            int nextTerm = firstTerm + secondTerm;
            // Update the values for the next iteration
            firstTerm = secondTerm;
            secondTerm = nextTerm;
        }

        // Close the scanner object
        scanner.close();
    }
}

Output

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

Explanation

  • The program uses a Scanner to help the user with the number of terms in the Fibonacci series.
  • It initializes the first two terms of the series as 0 and 1.
  • A loop runs n times to generate and print each term of the Fibonacci series, updating the terms with each iteration.
  • Finally, the Scanner object is closed to free up resources.

Fibonacci Series Program in Java Using Recursion

We can use the recursive method to produce the fibonacci series in Java. We can use it to design a Java method that calls itself to compute the Fibonacci number at a particular point.

Example

import java.util.Scanner;

public class FibonacciRecursion {
    public static int fibonacci(int n) {
        if (n <= 1) {
            return n; 
        }
        return fibonacci(n - 1) + fibonacci(n - 2); // Recursive case
    }

    public static void main(String[] args) {
        // Create a Scanner object to read input
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the number of terms: ");
        int n = scanner.nextInt();

        System.out.println("Fibonacci Series up to " + n + " terms:");

        for (int i = 0; i < n; i++) {
            System.out.print(fibonacci(i) + " ");
        }

        // Close the scanner object
        scanner.close();
    }
}

Output

Enter the number of terms: 5
Fibonacci Series up to 5 terms:
0 1 1 2 3 

Explanation

  • Use recursive method fibonacci(int n) to calculate each Fibonaccie lements, with base cases returning 0 and 1 and the recursive case adding the previous two numbers.
  • User provides the number of terms, and a loop iteratively calls the fibonacci method to printteh series.
  • We useScanner object to read user input and is closed at the end to free up resources.

Implementing Fibonacci Series in Java Using For Loop

The following is a basic iterative technique you may use with a for loop in Java to construct the Fibonacci sequence.

Example

import java.util.Scanner;

public class FibonacciForLoop {
    public static void main(String[] args) {
        // Create a Scanner object to read input
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the number of terms: ");
        int n = scanner.nextInt();

        // Variables to store the first two terms
        int firstTerm = 0, secondTerm = 1;

        System.out.println("Fibonacci Series of " + n + " terms:");

        for (int i = 0; i < n; ++i) {
            // Print the current term
            System.out.print(firstTerm + " ");

            // Compute the next term
            int nextTerm = firstTerm + secondTerm;
            // Update the terms for the next iteration
            firstTerm = secondTerm;
            secondTerm = nextTerm;
        }

        // Close the scanner object
        scanner.close();
    }
}

Output

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

Explanation

  • By using a Scanner object, The application assists the user in entering the Fibonacci series' term count.
  • A for loop iterates n times, printing the current Fibonacci term and updating the terms for the next iteration.
  • It gives another element by addingfirstTerm and secondTerm, updates firstTerm and secondTerm, and then prints the series.

Fibonacci Series in Java Using While Loop

Awhile loop helps to generate the fibonacci series in Java. This method is used to print the each element one after the other, until we could not get the desired output.

Example

import java.util.Scanner;

public class FibonacciWhileLoop {
    public static void main(String[] args) {
        // Create a Scanner object to read input
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the number of terms: ");
        int n = scanner.nextInt();

        // Variables to store the first two terms
        int firstTerm = 0, secondTerm = 1;

        System.out.println("Fibonacci Series up to " + n + " terms:");

        int count = 0;

        // Generate and print the Fibonacci series using a while loop
        while (count < n) {
            System.out.print(firstTerm + " "); // Print the current term

            // Compute the next term
            int nextTerm = firstTerm + secondTerm;
            // Update the terms for the next iteration
            firstTerm = secondTerm;
            secondTerm = nextTerm;

            // Increment the counter
            count++;
        }

        // Close the scanner object
        scanner.close();
    }
}

Output

Enter the number of terms: 8
Fibonacci Series up to 8 terms:
0 1 1 2 3 5 8 13

Explanation

  • The program helps the user to enter the number of Fibonacci terms to generate and store this value in n.
  • It uses a while loop to print each Fibonacci term up to the number specified, updating the terms and counter in each iteration.
  • The next Fibonacci term is calculated as the sum of the current two terms firstTerm and secondTerm, and the loop continues until the desired number of terms is printed.

Fibonacci Series Using Memoization

Recursive algorithms are optimized using memorization, which prevents repetitive computations by retaining previously computed results. It improves performance for the Fibonacci sequence by caching and reusing Fibonacci numbers.

Example

import java.util.HashMap;
import java.util.Map;

public class FibonacciMemoization {
    // Map to store previously computed Fibonacci numbers
    private static Map<Integer, Integer> memo = new HashMap<>();

    public static int fibonacci(int n) {
        // Base cases
        if (n <= 1) {
            return n;
        }
        
        // Check if the value is already computed and stored in the map
        if (memo.containsKey(n)) {
            return memo.get(n);
        }
        
        // Compute the value and store it in the map
        int result = fibonacci(n - 1) + fibonacci(n - 2);
        memo.put(n, result);
        return result;
    }

    public static void main(String[] args) {
        int n = 10; 

        System.out.println("Fibonacci Series up to " + n + " terms:");

       for (int i = 0; i < n; i++) {
            System.out.print(fibonacci(i) + " ");
        }
    }
}

Output

Fibonacci Series up to 10 terms:
0 1 1 2 3 5 8 13 21 34

Explanation

  • We use a HashMap to store and reuse previously calculated Fibonacci numbers that helps in speeding up the computation.
  • the fibonacci technique first verifies the map before calculating each Fibonacci number iteratively.
  • The main method prints the first 10 Fibonacci numbers by calling the memoized fibonacci method in a loop.

Fibonacci Series Using Dynamic Programming

For deviding a complex problems in the smaller problems, we use the dynamic approach to solve it. Every subproblem is solved by only one time and the result will be stored for the future use.

Example

public class FibonacciDynamicProgramming {
    public static void main(String[] args) {
        int n = 6; 

        // Array to store Fibonacci numbers
        int[] fib = new int[n];

        // Base cases
        if (n > 0) fib[0] = 0;
        if (n > 1) fib[1] = 1;

        // Fill the array using the dynamic programming approach
        for (int i = 2; i < n; i++) {
            fib[i] = fib[i - 1] + fib[i - 2];
        }

        System.out.println("Fibonacci sequence of " + n + " terms:");
        for (int i = 0; i < n; i++) {
            System.out.print(fib[i] + " ");
        }
    }
}

Example

Fibonacci sequence of 6 terms:
0 1 1 2 3 5 

Explanation

  • Define an array namefib to store the Fibonacci sequence, and create the first two elements (fib[0] and fib[1]) based on the base cases.
  • Using the for loop to save the remaining of the array by using the Fibonacci formula fib[i] = fib[i - 1] + fib[i - 2].
  • By iterating through the nth times, the result will be printed.
Read More:
Relational operators in Java
Constructor Overloading in Java
Hierarchical Inheritance in Java

Fibonacci Series Using Iterative Approach

The Fibonacci sequence is computed iteratively by using a loop to calculate each term consecutively and without recursion. It is an easy and effective method to create the Fibonacci sequence by thefixed number of terms.

Example

public class FibonacciIterative {
    public static void main(String[] args) {
        int n = 9;

        // Variables to store the first two terms
        int firstTerm = 0, secondTerm = 1;

        System.out.println("Fibonacci Series " + n + " terms:");

        for (int i = 0; i < n; i++) {
            System.out.print(firstTerm + " ");

            // Compute the next term
            int nextTerm = firstTerm + secondTerm;
            // Update the terms for the next iteration
            firstTerm = secondTerm;
            secondTerm = nextTerm;
        }
    }
}

Output

Fibonacci Series 9 terms:
0 1 1 2 3 5 8 13 21

Explanation

  • We start the first two numbers ob the Fibonacci series that arefirstTerm to 0 and secondTerm to 1.
  • The for loop go throughn times, and it will printfirstTerm and then updating firstTerm and secondTerm to the following values in the sequence.
  • Computes the next term as the sum of firstTerm and secondTerm, and updates the variables for the next iteration.

Fibonacci Series Using Static Variable

We use the static variable in Java to generate a Fibonacci series. This method becomes very useful when you want to manage a state across multiple method calls or instances of a class. This method uses a static variable to record the current value or condition.

Example

public class FibonacciStatic {
    // Static variables to store the current and next terms
    private static int firstTerm = 0;
    private static int secondTerm = 1;

    // Method to get the next Fibonacci number
    public static int getNextFibonacci() {
        int nextTerm = firstTerm + secondTerm;
        // Update the terms for the next call
        firstTerm = secondTerm;
        secondTerm = nextTerm;
        return firstTerm;
    }

    public static void main(String[] args) {
        int n = 9; // generate the numbers of terms

        System.out.println("Fibonacci Series up to " + n + " terms:");
        for (int i = 0; i < n; i++) {
            System.out.print(getNextFibonacci() + " ");
        }
    }
}

Output

Fibonacci Series up to 9 terms:
1 1 2 3 5 8 13 21 34 

Explanation

  • firstTerm and secondTerm are static variables used to keep track of the current and next Fibonacci terms across method calls.
  • getNextFibonacci() computes the next Fibonacci number, updates the static variables, and returns the current term.
  • The main method calls getNextFibonacci() in a loop to print the first n Fibonacci numbers, with n set to 9.

Fibonacci Series Using Direct Formula

By using Binet's formula, we don't need to use the recursion or iteration method. It helps us to generate the Fibonacci series in a quick way. The formula requires square roots and calculating powers and is based on mathematical constants.

The nth Fibonacci number F(n) can be defined by using this formula:

Example

public class FibonacciDirectFormula {
    public static void main(String[] args) {
        int n = 10; // Number of terms to generate

        System.out.println("Fibonacci Series up to " + n + " terms:");

        // Print Fibonacci series using the direct formula
        for (int i = 0; i < n; i++) {
            System.out.println(getFibonacci(i));
        }
    }

    // Method to calculate the nth Fibonacci number using Binet's formula
    public static long getFibonacci(int n) {
        // Constants for Binet's formula
        double sqrt5 = Math.sqrt(5);
        double phi = (1 + sqrt5) / 2;
        double psi = (1 - sqrt5) / 2;

        // Binet's formula to calculate Fibonacci number
        return Math.round((Math.pow(phi, n) - Math.pow(psi, n)) / sqrt5);
    }
}

Output

Fibonacci Series up to 10 terms:
0
1
1
2
3
5
8
13
21
34

Explanation

  • uses Binet's formula with constants phi and psi to compute the nth Fibonacci number directly.
  • Math.pow() calculates powers, and Math.round() ensures the result is rounded to the nearest integer for accuracy.
  • The main method prints the first n Fibonacci numbers by calling getFibonacci() in a loop.
Conclusion
In conclusion, we have discussed the Fibonacci series in Java, including different methods to generate the Fibonacci series. By selecting the best approach depending on the specifications of the issue and performance factors, you may improve your comprehension of algorithm design and optimization in Java. If you want to make your career as a Java developer, Scholorhat provides you with a Java Full Stack Course that you can join to make a brighter future.

FAQs

The Fibonacci series has several applications in programming and computer science due to its mathematical properties and its use in various algorithms and problem-solving scenarios.
  • Algorithm Design
  • Computational Complexity 
  • Data Structure
  • Optimization Problems 

A Fibonacci time series is a sequence where each time step or interval follows the Fibonacci pattern, often used in financial markets to model periodic cycles or trends. It applies Fibonacci numbers to time intervals, helping to analyze and forecast patterns in data.

Fibonacci heap is a data structure that provides efficient support for priority queue operations, including merging heaps and decreasing keys. It uses a collection of heap-ordered trees to optimize performance in algorithms like Dijkstra's shortest path

To write a Fibonacci series program in Java, you can use either iterative or recursive methods to compute the sequence. Initialize the first two terms and use loops or recursion to generate and print subsequent terms. 
Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 9th time in a row (2016-2024). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this