Java Program to Find the Fibonacci Series

1. Introduction

The Fibonacci series is a sequence of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. Writing a Java program to find the Fibonacci series is a common exercise for learning loops and conditionals in Java.

2. Program Steps

1. Import the Scanner class from the java.util package for user input.

2. Define the main class named FibonacciSeries.

3. Inside the main class, define the main method.

4. Inside the main method, create an object of the Scanner class to take user input.

5. Prompt the user to enter the number of terms in the Fibonacci series.

6. Initialize the first two terms of the Fibonacci series.

7. Use a for loop to calculate the Fibonacci series up to the user-specified number of terms.

8. Print each term of the Fibonacci series.

3. Code Program

import java.util.Scanner; // 1. Importing Scanner class for user input

public class FibonacciSeries { // 2. Defining the main class

    public static void main(String[] args) { // 3. Defining the main method

        Scanner input = new Scanner(System.in); // 4. Creating Scanner object to take user input

        System.out.print("Enter the number of terms in the Fibonacci series: "); // 5. Prompting user for the number of terms
        int terms = input.nextInt(); // Storing the number of terms in variable terms

        int firstTerm = 0, secondTerm = 1; // 6. Initializing the first two terms of the Fibonacci series

        // 7. Calculating and printing the Fibonacci series up to the user-specified number of terms
        for (int i = 1; i <= terms; i++) {
            System.out.print(firstTerm + " "); // 8. Printing each term of the Fibonacci series
            int nextTerm = firstTerm + secondTerm;
            firstTerm = secondTerm;
            secondTerm = nextTerm;
        }

        input.close(); // Closing the Scanner object to avoid memory leak
    }
}

Output:

Enter the number of terms in the Fibonacci series: 7
0 1 1 2 3 5 8

4. Step By Step Explanation

Step 1: The Scanner class from the java.util package is imported, which allows the program to read user input.

Step 2: The main class, FibonacciSeries, is defined.

Step 3: The main method, which serves as the entry point of the program, is defined within the main class.

Step 4: A Scanner object named "input" is created to facilitate user input.

Step 5: The user is prompted to enter the number of terms in the Fibonacci series, which is stored in the variable terms.

Step 6: The first two terms of the Fibonacci series, 0 and 1, are initialized.

Step 7: A for loop is used to calculate each term of the Fibonacci series up to the 7th term, as specified by the user.

Step 8: Each term of the Fibonacci series is printed out: 0 1 1 2 3 5 8.

Lastly, the Scanner object is closed to avoid potential memory leaks.

Comments