w3resource

Fibonacci Sequence Generator in Java: Loops and Recursion


Java Project - Fibonacci Sequence:

Fibonacci Sequence Generator :

Generate the first N numbers of the Fibonacci sequence.

The program generates and displays the first N numbers in the Fibonacci sequence, where each number is the sum of the two preceding ones, starting from 0 and 1.

Input: Number of terms.
Output: First N numbers in the Fibonacci sequence.

Example:

  • Input: 7
  • Output: 0, 1, 1, 2, 3, 5, 8

Solution 1: Fibonacci Sequence Using Loops

Code:

import java.util.Scanner;

public class FibonacciUsingLoop {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Taking user input for the number of terms
        System.out.print("Enter the number of terms: ");
        int n = scanner.nextInt();
        
        // Initialize the first two Fibonacci numbers
        int num1 = 0, num2 = 1;
        
        // Display the first N Fibonacci numbers
        System.out.print("Fibonacci Sequence: " + num1);
        
        if (n > 1) {
            System.out.print(", " + num2);
        }

        // Generate Fibonacci numbers using a loop
        for (int i = 3; i <= n; i++) {
            int nextNum = num1 + num2; // The next number is the sum of the previous two
            System.out.print(", " + nextNum);
            num1 = num2;  // Update num1
            num2 = nextNum; // Update num2
        }
        
        System.out.println(); // Newline for better output formatting
        scanner.close(); // Closing the scanner resource
    }
}

Output:

Enter the number of terms:  10
Fibonacci Sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34

Explanation :

  • Input and Scanner: The program prompts the user to input the number of terms (n) to generate in the Fibonacci sequence.
  • Initial Variables: Two variables num1 and num2 are initialized to represent the first two Fibonacci numbers (0 and 1).
  • Display First Two Numbers: If the user requests more than one term, the first two Fibonacci numbers are displayed.
  • For Loop: The loop iterates from 3 to n, generating the next Fibonacci number by summing the two preceding numbers and printing the result.
  • Variable Updates: In each iteration, the previous two numbers are updated to continue generating the sequence.
  • Close Scanner: The scanner is closed to free up system resources.

Solution 2: Fibonacci Sequence Using Recursion

Code:

import java.util.Scanner;

public class FibonacciUsingRecursion {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Taking user input for the number of terms
        System.out.print("Enter the number of terms: ");
        int n = scanner.nextInt();
        
        System.out.print("Fibonacci Sequence: ");
        for (int i = 0; i < n; i++) {
            System.out.print(fibonacci(i));
            if (i < n - 1) {
                System.out.print(", ");
            }
        }

        System.out.println(); // Newline for better output formatting
        scanner.close(); // Closing the scanner resource
    }

    // Recursive method to find the nth Fibonacci number
    public static int fibonacci(int n) {
        if (n == 0) { // Base case: Fibonacci(0) is 0
            return 0;
        } else if (n == 1) { // Base case: Fibonacci(1) is 1
            return 1;
        } else {
            return fibonacci(n - 1) + fibonacci(n - 2); // Recursive call
        }
    }
}  

Output:

Enter the number of terms:  7
Fibonacci Sequence: 0, 1, 1, 2, 3, 5, 8

Explanation:

  • Input and Scanner: The program prompts the user to input the number of terms (n) to generate in the Fibonacci sequence.
  • Recursive Function: The fibonacci() function is a recursive method that calculates the nth Fibonacci number. The base cases are fibonacci(0) = 0 and fibonacci(1) = 1.
  • For Loop: The loop iterates from 0 to n-1, calling the recursive function to print each Fibonacci number in sequence.
  • Recursion: For any n greater than 1, the function returns the sum of the previous two Fibonacci numbers (fibonacci(n-1) + fibonacci(n-2)).
  • Display Sequence: The generated numbers are displayed in the desired format, separated by commas.
  • Close Scanner: The scanner is closed to free up system resources.

Java Code Editor:




Follow us on Facebook and Twitter for latest update.