Write A Program To Generate Fibonacci Series Upto N Terms In Java
The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. This article will guide you through generating the Fibonacci series up to a specified number of terms in Java.
Problem Statement
Generating the Fibonacci series involves calculating a sequence of numbers where each subsequent number is derived from the sum of the previous two. The challenge is to implement this logic efficiently and correctly for a given number of terms, n.
Example
For n = 5, the Fibonacci series would be: 0, 1, 1, 2, 3
Background & Knowledge Prerequisites
To understand this article, you should have a basic understanding of:
- Java syntax and data types.
-
forandwhileloops. - Conditional statements (
if-else). - Input/output operations using
Scanner.
Use Cases or Case Studies
The Fibonacci sequence appears in various fields:
- Computer Science: Used in algorithms like Fibonacci search and Fibonacci heaps.
- Mathematics: Demonstrates properties of recursive sequences and the golden ratio.
- Nature: Observed in the branching of trees, arrangement of leaves on a stem, and the uncurling of a fern.
- Financial Markets: Used in technical analysis to predict price movements.
- Art and Architecture: Applied in design for aesthetic proportions.
Solution Approaches
We will explore two common approaches to generate the Fibonacci series: using a for loop and using a while loop.
Approach 1: Using a for loop
This approach iteratively calculates each Fibonacci number and prints it until the desired number of terms is reached.
One-line summary: Iterates a fixed number of times to calculate and print Fibonacci numbers.
// Fibonacci Series using for loop
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
// Step 1: Initialize Scanner for user input
Scanner scanner = new Scanner(System.in);
// Step 2: Prompt user for the number of terms
System.out.print("Enter the number of terms (n): ");
int n = scanner.nextInt();
// Step 3: Initialize the first two Fibonacci numbers
int a = 0;
int b = 1;
// Step 4: Handle edge cases for n = 0, 1, 2
if (n <= 0) {
System.out.println("Please enter a positive integer.");
} else if (n == 1) {
System.out.println("Fibonacci Series up to 1 term: " + a);
} else {
// Step 5: Print the first two terms
System.out.print("Fibonacci Series up to " + n + " terms: " + a + ", " + b);
// Step 6: Generate subsequent terms using a for loop
for (int i = 2; i < n; i++) {
int nextTerm = a + b;
System.out.print(", " + nextTerm);
a = b;
b = nextTerm;
}
System.out.println(); // New line for better formatting
}
// Step 7: Close the scanner
scanner.close();
}
}
Sample output:
Enter the number of terms (n): 7
Fibonacci Series up to 7 terms: 0, 1, 1, 2, 3, 5, 8
Stepwise explanation:
- Initialize
Scanner: Creates an object to read input from the console. - Get
n: Prompts the user to enter the number of terms and stores it inn. - Initialize
aandb: Sets the first two Fibonacci numbers,a = 0andb = 1. - Handle edge cases:
- If
nis non-positive, it prints an error. - If
nis 1, it prints only the first term (0).
- Print initial terms: For
n > 1, it printsaandbas the starting point of the series. - Loop for subsequent terms:
- A
forloop runs fromi = 2up ton-1(since the first two terms are already printed). -
nextTermis calculated as the sum ofaandb. -
nextTermis printed. -
ais updated to the value ofb. -
bis updated to the value ofnextTerm. This shifts the window to the next pair of numbers.
- Close
Scanner: Releases system resources.
Approach 2: Using a while loop
This approach also iteratively calculates the Fibonacci numbers, but uses a while loop, which can be useful when the number of iterations is not strictly fixed beforehand (though in this case, it is).
One-line summary: Continuously calculates and prints Fibonacci numbers until a counter reaches the desired number of terms.
```java // Program Title: Fibonacci Series using while loop import java.util.Scanner;
// Main class containing the entry point of the program public class Main { public static void main(String[] args) { // Step 1: Initialize Scanner for user input Scanner scanner = new Scanner(System.in);
// Step 2: Prompt user for the number of terms System.out.print("Enter the number of terms (n): "); int n = scanner.nextInt();
// Step 3: Initialize the first two Fibonacci numbers and a counter int a = 0; int b = 1; int count = 0; // To keep track of the number of terms printed
// Step 4: Handle edge cases for n = 0 if (n <= 0) { System.out.println("Please enter a positive integer."); } else { System.out.print("Fibonacci Series up to " + n + " terms: ");
// Step 5: Generate terms using a while loop while (count < n) { System.out.print(a); if (count < n - 1) { // Add comma only if it's not the last term System.out.print(", "); }
int nextTerm = a + b; a