Java Program to Print Fibonacci Series
The Fibonacci series is a sequence in which each term after the first two is the sum of the previous two terms. When the sequence starts with 0 and 1, the first few terms are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34.
In Java, you can generate the Fibonacci series using a for loop, a while loop, recursion, or a loop that stops when a specified maximum value is reached. The examples below cover these common approaches.
Fibonacci Series using For Loop
In this example, we shall use Java For Loop to generate an array with given number of terms of Fibonacci series.
Java Program
/**
* Java Program - Fibonacci
* 0 1 1 2 3 5 8 13 21 34 55 . .
*/
public class Fibonacci {
public static void main(String[] args) {
int nterms = 10;
int[] fibo = new int[nterms];
for (int index=0; index < fibo.length; index++) {
if(index==0) {
fibo[index] = 0;
} else if(index==1) {
fibo[index] = 1;
} else {
fibo[index] = fibo[index-1] + fibo[index-2];
}
}
//print fibonacci series
for(int n:fibo)
System.out.print(n+" ");
}
}
Output
0 1 1 2 3 5 8 13 21 34
The array stores every generated Fibonacci number. For index 0, the value is set to 0; for index 1, it is set to 1; every later value is calculated from the previous two array elements.
Algorithm to print Fibonacci series of n terms
We shall use the following algorithm to print Fibonacci series of n terms. You can use while loop or for loop to realize this algorithm.
- Start.
- Get the value of n in a variable
nTerms. We shall generate first n terms in Fibonacci series. - Take two variables n1 and n2. Initialize these with 0 and 1 respectively.
- Initialize i with 1.
- Check if i is less than or equal to
nTerms. If false go to step 9. - Print n1.
- Compute sum of n1 and n2, and load n1 with n2, and n2 with the sum.
- Increment i, and go to step 5.
- Stop.
The important update step is to calculate the next term before replacing the two previous values. Conceptually, if n1 and n2 are two consecutive Fibonacci numbers, then the next number is n1 + n2.
Fibonacci Series using For Loop and Without Array
In this example, we shall use Java For Loop to print given number of terms in a Fibonacci series.
Java Program
/**
* Java Program - Fibonacci
* 0 1 1 2 3 5 8 13 21 34 55 . .
*/
public class Fibonacci {
public static void main(String[] args) {
int nTerms = 10; //number of elements in fibonacci sequence
int n1 = 0, n2 = 1; //previous two elements
for (int i=1; i <= nTerms; i++) {
System.out.print(n1 + " ");
int n = n1 + n2;
n1 = n2;
n2 = n;
}
}
}
Output
0 1 1 2 3 5 8 13 21 34
This version does not store the complete sequence. It keeps only the two values required to calculate the next term, which is sufficient when the goal is simply to print the series.
Java Fibonacci Series up to n Terms using Scanner
If the number of Fibonacci terms should be entered at runtime, read nTerms with Scanner and then use the same iterative calculation. The following program prints exactly as many terms as the user requests.
import java.util.Scanner;
public class Fibonacci {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of terms: ");
int nTerms = scanner.nextInt();
int n1 = 0;
int n2 = 1;
for (int i = 1; i <= nTerms; i++) {
System.out.print(n1 + " ");
int next = n1 + n2;
n1 = n2;
n2 = next;
}
scanner.close();
}
}
For an input of 10, the program prints:
Enter number of terms: 10
0 1 1 2 3 5 8 13 21 34
Here, nTerms means the number of values to print. It does not mean the largest allowed Fibonacci value. Those are two different stopping conditions.
Fibonacci Series using While Loop
In this example, we shall use Java While Loop to print n terms of a Fibonacci series.
Java Program
/**
* Java Program - Fibonacci
* 0 1 1 2 3 5 8 13 21 34 55 . .
*/
public class Fibonacci {
public static void main(String[] args) {
int nTerms = 10; //number of elements in fibonacci sequence
int n1 = 0, n2 = 1; //previous two elements
int i=1;
while (i <= nTerms) {
System.out.print(n1 + " ");
int n = n1 + n2;
n1 = n2;
n2 = n;
i++;
}
}
}
Output
0 1 1 2 3 5 8 13 21 34
The while loop uses the same Fibonacci calculation as the previous example. The difference is that initialization and increment of the loop counter are written separately.
Java Fibonacci Series using Recursion
Fibonacci numbers can also be defined recursively. With zero-based indexing, F(0) = 0, F(1) = 1, and every later Fibonacci number is F(n) = F(n - 1) + F(n - 2).
F(0) = 0
F(1) = 1
F(n) = F(n - 1) + F(n - 2), for n >= 2
The following Java program uses that definition to print the first 10 Fibonacci terms.
public class Fibonacci {
static int fibonacci(int n) {
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
public static void main(String[] args) {
int nTerms = 10;
for (int i = 0; i < nTerms; i++) {
System.out.print(fibonacci(i) + " ");
}
}
}
0 1 1 2 3 5 8 13 21 34
This recursive version closely follows the mathematical definition, but the straightforward implementation repeatedly recalculates the same Fibonacci values. For simply generating a sequence of terms, the iterative loop versions are more direct.
Algorithm to print Fibonacci series with last term less than Given Number
We shall use the following algorithm to print Fibonacci series with last term less than a given maximum limit. You can use while loop or for loop to realize this algorithm.
- Start.
- Get the value of maximum limit of Fibonacci term in a variable
max. - Take two variables
n1andn2. Initialize these with 0 and 1 respectively. - Initialize
iwith1. - Check if
n1is less thanmax. If false go to step 9. - Print
n1. - Compute sum of
n1andn2, and loadn1withn2, andn2with the sum. - Increment
i, and go to step 5. - Stop.
Fibonacci Series with Last Term less than Given Number
In this example, we shall print all the terms of a Fibonacci series whose last term is less than a given maximum limit.
Java Program
/**
* Java Program - Fibonacci
* 0 1 1 2 3 5 8 13 21 34 55 . .
*/
public class Fibonacci {
public static void main(String[] args) {
int max = 100; //number of elements in fibonacci sequence
int n1 = 0, n2 = 1; //previous two elements
for (int i=1; n1 < max; i++) {
System.out.print(n1 + " ");
int n = n1 + n2;
n1 = n2;
n2 = n;
}
}
}
Output
0 1 1 2 3 5 8 13 21 34 55 89
Because the loop condition is n1 < max, a value equal to max would not be printed. With max = 100, the largest printed Fibonacci number is 89, because the next term is 144.
Java Fibonacci Series from 1 to 100
If the requirement is specifically to print Fibonacci numbers from 1 through 100, start with 1 and keep printing while the current term is less than or equal to 100.
public class Fibonacci {
public static void main(String[] args) {
int n1 = 1;
int n2 = 1;
while (n1 <= 100) {
System.out.print(n1 + " ");
int next = n1 + n2;
n1 = n2;
n2 = next;
}
}
}
1 1 2 3 5 8 13 21 34 55 89
This is different from printing the first 100 terms. Here, 100 is a maximum value, not a term count.
Fibonacci Series using For Loop and Reduced Lines of Code
From the previous example, we shall rearrange the code such that, we have fewer lines of code in and around for loop.
Java Program
/**
* Java Program - Fibonacci
* 0 1 1 2 3 5 8 13 21 34 55 . .
*/
public class Fibonacci {
public static void main(String[] args) {
int max = 100; //max term in Fibonacci sequence
for (int n1 = 0, n2 = 1, n; n1 <= max; n=n1+n2, n1=n2, n2=n)
System.out.print(n1 + " ");
}
}
Output
0 1 1 2 3 5 8 13 21 34 55 89
This compact form places initialization and the Fibonacci update expressions in the for statement itself. The longer loop versions are generally easier to follow when first learning how the sequence is generated.
How the Fibonacci Variable Update Works in Java
The iterative programs repeatedly perform the same three-step update. Suppose n1 = 3 and n2 = 5. The next Fibonacci number is 8. After the update, the pair becomes 5 and 8, ready to calculate 13.
next = n1 + n2;
n1 = n2;
n2 = next;
A temporary variable such as next is useful because the original values of both n1 and n2 are needed before they are replaced.
Choosing a Java Fibonacci Program by Requirement
- Use a
forloop when the number of Fibonacci terms is already known. - Use
Scannerwith a loop when the user should enter the number of terms. - Use a
whileloop when the stopping condition is easier to express independently of a loop counter. - Use a value-based condition such as
n1 < maxwhen the sequence must stop before a maximum number. - Use recursion when demonstrating the recursive Fibonacci definition, while remembering that the straightforward recursive version performs repeated calculations.
- Use an array only when the generated Fibonacci values need to be retained for later access.
Java Fibonacci Series Summary
In this Java Tutorial, we learned how to write Java Programs using looping statements to generate Fibonacci Series.
For most iterative Fibonacci programs, start with 0 and 1, print the current value, calculate the sum of the two current terms, and shift the pair forward. The loop condition determines whether the program prints a fixed number of terms or all Fibonacci values below a specified limit.
TutorialKart.com