Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. Writing a Java program to generate the Fibonacci series is a fundamental coding exercise, and it can be efficiently accomplished using a while loop.
Here’s a step-by-step guide to write a Java program to generate the Fibonacci series:
Fibonacci Series Program in Java
package com.gangforcode;
import java.util.Scanner;
public class FibonacciSeries {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of terms for Fibonacci series: ");
int count = scanner.nextInt();
int firstTerm = 0, secondTerm = 1;
int i = 1;
System.out.println("Fibonacci Series:");
while (i <= count) {
System.out.print(firstTerm + " ");
int nextTerm = firstTerm + secondTerm;
firstTerm = secondTerm;
secondTerm = nextTerm;
i++;
}
}
}
Output
Explanation of Fibonacci Series Code
- Importing Required Package:
import java.util.Scanner;
– This line imports the Scanner class from thejava.util
package to take user input. - Taking Input:
Scanner scanner = new Scanner(System.in);
– It initializes the Scanner object to read user input from the console. - Prompt for User Input:
System.out.print("Enter the number of terms for Fibonacci series: ");
– Asks the user to input the number of terms in the Fibonacci series. - Generating Fibonacci Series: The ‘while’ loop is used to generate the Fibonacci series based on the number of terms entered by the user. Inside the loop:
System.out.print(firstTerm + " ");
– Prints the current term of the Fibonacci series.int nextTerm = firstTerm + secondTerm;
– Calculates the next term by adding the previous two terms.firstTerm = secondTerm;
andsecondTerm = nextTerm;
– Update the values of firstTerm and secondTerm for the next iteration.i++;
– Increment the loop counter.
- Printing the Series: The loop continues until the desired number of terms are printed.
- Closing Scanner:
scanner.close();
– It closes the Scanner object to free up resources after finishing the input reading process.
How to Run the Java Program
- Copy the provided Java code into a text editor or an Integrated Development Environment (IDE) like Eclipse, IntelliJ, or NetBeans.
- Save the file with the extension “.java” (e.g., FibonacciSeries.java).
- Compile and run the program using the Java compiler or IDE.