WAP in Java to Print Fibonacci Series

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.

Wap in java

Here’s a step-by-step guide to write a Java program to generate the Fibonacci series:

Fibonacci Series Program in Java

Output

wap in java to print fibonacci series

Explanation of Fibonacci Series Code

  1. Importing Required Package: import java.util.Scanner; – This line imports the Scanner class from the java.util package to take user input.
  2. Taking Input: Scanner scanner = new Scanner(System.in); – It initializes the Scanner object to read user input from the console.
  3. 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.
  4. 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; and secondTerm = nextTerm; – Update the values of firstTerm and secondTerm for the next iteration.
  • i++; – Increment the loop counter.
  1. Printing the Series: The loop continues until the desired number of terms are printed.
  2. 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

  1. Copy the provided Java code into a text editor or an Integrated Development Environment (IDE) like Eclipse, IntelliJ, or NetBeans.
  2. Save the file with the extension “.java” (e.g., FibonacciSeries.java).
  3. Compile and run the program using the Java compiler or IDE.

See Also

Leave a Comment