Fibonacci Series in Java using Recursion and Loops
โก Smart Summary
Fibonacci Series in Java generates a sequence where every term equals the sum of the two terms before it. This article presents for loop, while loop, user input, recursive, and memoized programs, traces the recursion, and compares the time complexity of each approach.

What is Fibonacci Series in Java?
A Fibonacci Series in Java is a series of numbers in which the next number is the sum of the previous two numbers. The first two numbers of the Fibonacci series are 0 and 1. The Fibonacci numbers are significantly used in the computational run-time study of the algorithm that determines the greatest common divisor of two integers.
The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...
Expressed as a formula, the rule is F(n) = F(n-1) + F(n-2), with F(0) = 0 and F(1) = 1. The table below shows how the first eight terms are produced.
| Position (n) | Calculation | Value |
|---|---|---|
| 0 | Base case | 0 |
| 1 | Base case | 1 |
| 2 | 0 + 1 | 1 |
| 3 | 1 + 1 | 2 |
| 4 | 1 + 2 | 3 |
| 5 | 2 + 3 | 5 |
| 6 | 3 + 5 | 8 |
| 7 | 5 + 8 | 13 |
Fibonacci Series Program in Java using For Loop
The iterative version keeps only two values in memory at any moment, which is why it runs in linear time and constant space.
//Using For Loop
public class FibonacciExample {
public static void main(String[] args)
{
// Set it to the number of elements you want in the Fibonacci Series
int maxNumber = 10;
int previousNumber = 0;
int nextNumber = 1;
System.out.print("Fibonacci Series of "+maxNumber+" numbers:");
for (int i = 1; i <= maxNumber; ++i)
{
System.out.print(previousNumber+" ");
/* On each iteration, we are assigning second number
* to the first number and assigning the sum of last two
* numbers to the second number
*/
int sum = previousNumber + nextNumber;
previousNumber = nextNumber;
nextNumber = sum;
}
}
}
Output:
Fibonacci Series of 10 numbers:0 1 1 2 3 5 8 13 21 34
Program Logic:
- previousNumber is initialized to 0 and nextNumber is initialized to 1.
- The Fibonacci for loop iterates through
maxNumber:- Display the previousNumber.
- Calculate the sum of previousNumber and nextNumber.
- Update the new values of previousNumber and nextNumber.
Fibonacci Series Program in Java using While Loop
You can also generate a Java Fibonacci series using a while loop in Java. The arithmetic is identical, and only the loop syntax changes.
//Using While Loop
public class FibonacciWhileExample {
public static void main(String[] args)
{
int maxNumber = 10, previousNumber = 0, nextNumber = 1;
System.out.print("Fibonacci Series of "+maxNumber+" numbers:");
int i=1;
while(i <= maxNumber)
{
System.out.print(previousNumber+" ");
int sum = previousNumber + nextNumber;
previousNumber = nextNumber;
nextNumber = sum;
i++;
}
}
}
Output:
Fibonacci Series of 10 numbers:0 1 1 2 3 5 8 13 21 34
The only difference in the program logic is the use of a while loop to print the Fibonacci numbers. The counter must be declared before the loop and incremented inside it, otherwise the loop never ends.
Fibonacci Series Based On The User Input
Hard-coding the term count is convenient for a demonstration, but real exercises usually read the value from the keyboard. The Scanner class handles that in three lines, and the generation logic stays untouched.
//fibonacci series based on the user input import java.util.Scanner; public class FibonacciUserInput { public static void main(String[] args) { int maxNumber = 0; int previousNumber = 0; int nextNumber = 1; System.out.println("How many numbers you want in Fibonacci:"); Scanner scanner = new Scanner(System.in); maxNumber = scanner.nextInt(); System.out.print("Fibonacci Series of " + maxNumber + " numbers:"); for (int i = 1; i <= maxNumber; ++i) { System.out.print(previousNumber + " "); /* On each iteration, we are assigning the second number * to the first number and assigning the sum of the last two * numbers to the second number */ int sum = previousNumber + nextNumber; previousNumber = nextNumber; nextNumber = sum; } scanner.close(); } }
Sample Run:
How many numbers you want in Fibonacci: 7 Fibonacci Series of 7 numbers:0 1 1 2 3 5 8
Program Logic:
The logic is the same as earlier. Instead of hardcoding the number of elements to show in the Java Fibonacci series, the user is asked to enter a number.
Fibonacci Series Using Recursion in Java
Below is a Fibonacci series program in Java using recursion:
//Using Recursion
public class FibonacciCalc{
public static int fibonacciRecursion(int n){
if(n == 0){
return 0;
}
if(n == 1 || n == 2){
return 1;
}
return fibonacciRecursion(n-2) + fibonacciRecursion(n-1);
}
public static void main(String args[]) {
int maxNumber = 10;
System.out.print("Fibonacci Series of "+maxNumber+" numbers: ");
for(int i = 0; i < maxNumber; i++){
System.out.print(fibonacciRecursion(i) +" ");
}
}
}
Output:
Fibonacci Series of 10 numbers: 0 1 1 2 3 5 8 13 21 34
Program Logic:
A recursive function is one that has the capability to call itself.
fibonacciRecursion():
- The Java Fibonacci recursion function takes an input number. It checks for 0, 1, and 2 and returns 0, 1, 1 respectively, because the Fibonacci sequence in Java starts with 0, 1, 1.
- When the input n is 3 or greater, the function calls itself recursively. The call is made twice. The trace below follows the call for an input of 4.
fibonacciRecursion(4)
= fibonacciRecursion(2) + fibonacciRecursion(3)
fibonacciRecursion(2) = 1 // base case, no further calls
fibonacciRecursion(3) = fibonacciRecursion(1) + fibonacciRecursion(2)
= 1 + 1
= 2
Result: 1 + 2 = 3
The base cases stop the descent. Because 1 and 2 both return immediately, the branch for fibonacciRecursion(2) never expands further, which is what keeps the trace finite.
Optimized Fibonacci Series Using Memoization
Plain recursion recomputes the same terms many times. Computing term 40 requires more than 200 million calls. Storing each result the first time it is calculated removes that duplication entirely.
public class FibonacciMemo { static long[] cache; public static long fib(int n) { if (n <= 1) { return n; } // return the stored value when it exists if (cache[n] != 0) { return cache[n]; } cache[n] = fib(n - 1) + fib(n - 2); return cache[n]; } public static void main(String[] args) { int maxNumber = 90; cache = new long[maxNumber + 1]; System.out.println("Term 50 is: " + fib(50)); System.out.println("Term 90 is: " + fib(90)); } }
Output:
Term 50 is: 12586269025 Term 90 is: 2880067194370816120
โ ๏ธ Warning: The 47th Fibonacci term is 2971215073, which exceeds the int maximum of 2147483647 and wraps to a negative value. Declare the variables as long once the count passes 46, and switch to BigInteger beyond term 92.
Comparison of Fibonacci Methods in Java
All four programs print the same sequence, so the decision rests on how many terms are needed.
| Method | Time Complexity | Space Complexity | Practical Limit |
|---|---|---|---|
| For loop | O(n) | O(1) | Any count, subject to the numeric type |
| While loop | O(n) | O(1) | Any count, subject to the numeric type |
| Plain recursion | O(2โฟ) | O(n) stack | Around 40 terms before it becomes slow |
| Recursion with memoization | O(n) | O(n) | Any count, subject to the numeric type |
The same counter and accumulator pattern appears in several related exercises. Continue with the Java palindrome program, the Java program to check a prime number, and the program to print prime numbers from 1 to 100. For array based practice, see Bubble Sort in Java and Java arrays, and review the for each loop in Java for alternative loop syntax.
