Java Program to Print Fibonacci Series
The Fibonacci series is a sequence in which each number is the sum of the two preceding ones. It is a popular programming problem used to teach loops and recursion in Java.
In this tutorial, we will create a Java program to generate the Fibonacci series up to a given number of terms.
By the end of this guide, you will understand how iterative logic is used to build sequences in Java.
Concept Overview
The Fibonacci series starts with 0 and 1. Each subsequent number is the sum of the previous two numbers.
Example: 0, 1, 1, 2, 3, 5, 8, 13, ...
Program
import java.util.Scanner;
public class FibonacciSeries {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of terms: ");
int n = sc.nextInt();
int first = 0, second = 1;
System.out.print("Fibonacci Series: ");
for (int i = 1; i <= n; i++) {
System.out.print(first + " ");
int next = first + second;
first = second;
second = next;
}
}
}
Output
Enter number of terms: 7
Fibonacci Series: 0 1 1 2 3 5 8
Detailed Explanation
The program begins by importing the Scanner class for user input.
Two variables, first and second, are initialized to 0 and 1 respectively.
The loop runs n times, printing the current number and calculating the next number.
Each new term is generated by adding the previous two terms.
Example Walkthrough
Let us consider n = 7.
The series generated is: 0 → 1 → 1 → 2 → 3 → 5 → 8.
Applications
Fibonacci series is used in algorithm design, dynamic programming, financial modeling, and computer graphics.
Advantages of This Approach
This program helps beginners understand loops and sequence generation.
It demonstrates how variables change dynamically during execution.
Limitations
The program is not optimized for very large values of n.
Improvements You Can Make
You can implement recursion to generate the series.
You can also use memoization for better performance.
This Java program provides a strong foundation in iterative problem solving and sequence generation.
Codecrown