Fibonacci Series in Java using with Recursion, Scanner, For & While Loop
The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, starting with 0 and 1 (0, 1, 1, 2, 3, 5, 8, 13...). It's a classic programming exercise that can be implemented in several ways in Java.
Fibonacci Series Using a for Loop
int n = 10;
int a = 0, b = 1;
for (int i = 0; i < n; i++) {
System.out.print(a + " ");
int next = a + b;
a = b;
b = next;
}
// 0 1 1 2 3 5 8 13 21 34
Fibonacci Series Using a while Loop
int n = 10, a = 0, b = 1, count = 0;
while (count < n) {
System.out.print(a + " ");
int next = a + b;
a = b;
b = next;
count++;
}
Fibonacci Series Using Recursion
A recursive method calls itself to compute each term based on the sum of the two previous terms, though it's less efficient for large values without optimization.
static int fibonacci(int n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
// usage
for (int i = 0; i < 10; i++) {
System.out.print(fibonacci(i) + " ");
}
Fibonacci Series with User Input Using Scanner
Scanner lets the program take the number of terms as input from the user at runtime, instead of hardcoding it.
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of terms: ");
int n = sc.nextInt();
int a = 0, b = 1;
for (int i = 0; i < n; i++) {
System.out.print(a + " ");
int next = a + b;
a = b;
b = next;
}
Comparing the Approaches
- Iterative (for/while) — efficient, runs in linear time, best for most use cases
- Recursive — elegant and easy to understand, but recalculates the same values repeatedly, making it slow for large
n - Scanner-based — adds interactivity by letting the user decide how many terms to generate
For large values of
n, the plain recursive approach becomes very slow — techniques like memoization can fix this, but the iterative loop version is usually the simplest efficient solution.Master Java with Uncodemy
Hands-on training, live projects, and placement support in our Java Programming Course.