Display Fibonacci Series in Java
What you’ll learn
- Definition using seeds
0and1. - How to print first
nterms iteratively. - How to print terms up to a maximum value.
Prerequisites
Basic Java loops and variables are enough for this page.
- Java loops and variables.
- Understand recurrence
F(k)=F(k-1)+F(k-2).
Definition
With seeds 0 and 1, each next term is the sum of the previous two.
Intuition
Keep two rolling values (a,b) and update (a,b) = (b, a+b).
Live preview
Print first n terms (uses BigInt for exact values).
Algorithm
Goal: print Fibonacci values in order using rolling pair updates.
Initialize
Set a = 0, b = 1.
Print current value
Output a as the next term.
Advance pair
Compute next = a + b, then shift a = b, b = next.
Repeat
Continue for required term count or until max limit.
📜 Pseudocode
function printFirstNFibonacci(n):
a = 0
b = 1
repeat n times:
output a
next = a + b
a = b
b = nextFirst n terms (n = 10)
public class Main {
static void displayFibonacciTerms(int n) {
int first = 0;
int second = 1;
if (n <= 0) {
System.out.println("Need a positive term count.");
return;
}
System.out.print("Fibonacci series up to " + n + " terms: ");
for (int i = 0; i < n; i++) {
if (i > 0) System.out.print(", ");
System.out.print(first);
int next = first + second;
first = second;
second = next;
}
System.out.println();
}
public static void main(String[] args) {
displayFibonacciTerms(10);
}
}Fibonacci series up to 10 terms: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
All terms <= 100
public class Main {
static void displayFibonacciUntil(int maxVal) {
int a = 0, b = 1;
boolean firstOut = true;
if (maxVal < 0) {
System.out.println("maxVal must be nonnegative.");
return;
}
System.out.print("Fibonacci numbers <= " + maxVal + ": ");
while (a <= maxVal) {
if (!firstOut) System.out.print(" ");
firstOut = false;
System.out.print(a);
int next = a + b;
a = b;
b = next;
}
System.out.println();
}
public static void main(String[] args) {
displayFibonacciUntil(100);
}
}Fibonacci numbers <= 100: 0 1 1 2 3 5 8 13 21 34 55 89
⏱️ Time and space complexity
| Task | Time | Extra space |
|---|---|---|
First n terms (iterative) | O(n) | O(1) |
All terms <= M | O(k), where k = O(log M) | O(1) |
Optimization note
For single F(n), matrix exponentiation or fast doubling gives O(log n).
🔄 Input / output examples
| n | Last printed term |
|---|---|
1 | 0 |
10 | 34 |
15 | 377 |
Edge cases
Empty series
n = 0 means no terms are printed.
Integer overflow
Large term indices can overflow int; use long or BigInteger.
Summary
- Iterative Fibonacci prints in
O(n)withO(1)extra space. - Track overflow when term values grow quickly.
❓ FAQ
The ratio of consecutive values F(k+1)/F(k) approaches the golden ratio phi = (1+sqrt(5))/2 for large k, which is why Fibonacci numbers grow so quickly.
8 people found this page helpful
