Fibonacci Series in Java
Last updated: February 8, 2025
The Fibonacci Series is one of the most popular sequences in mathematics and computer science. Each number in the Fibonacci sequence is the sum of the previous two numbers. In this blog, we will explore what the Fibonacci series is, how it works, and multiple Java programs to generate it efficiently.
What is the Fibonacci Series?
The Fibonacci sequence starts with:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
Mathematically, the series follows the formula:
F(n) = F(n - 1) + F(n - 2)
where:
F(0) = 0
F(1) = 1
Java Program: Fibonacci Using Loop
This is the most efficient and commonly used approach for beginners:
import java.util.Scanner;
public class FibonacciLoop {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of terms: ");
int n = sc.nextInt();
int a = 0, b = 1;
System.out.print("Fibonacci Series: ");
for (int i = 1; i <= n; i++) {
System.out.print(a + " ");
int next = a + b;
a = b;
b = next;
}
}
}
Fibonacci Using Recursion
The recursive approach is simple but not efficient for large inputs because it recalculates values repeatedly.
public class FibonacciRecursion {
public static int fib(int n) {
if (n <= 1)
return n;
return fib(n - 1) + fib(n - 2);
}
public static void main(String[] args) {
int n = 10;
System.out.print("Fibonacci Series: ");
for (int i = 0; i < n; i++) {
System.out.print(fib(i) + " ");
}
}
}
Optimized Fibonacci Using Dynamic Programming
A better recursive approach uses memoization to avoid repeated calculations:
public class FibonacciDP {
static int[] dp = new int[1000];
public static int fib(int n) {
if (n <= 1) return n;
if (dp[n] != 0) return dp[n];
dp[n] = fib(n - 1) + fib(n - 2);
return dp[n];
}
public static void main(String[] args) {
int n = 10;
System.out.print("Fibonacci Series: ");
for (int i = 0; i < n; i++) {
System.out.print(fib(i) + " ");
}
}
}
Conclusion
The Fibonacci series is an excellent exercise for understanding loops, recursion, and dynamic programming concepts. Beginners can start with the loop method, while advanced learners can experiment with recursive and optimized DP methods.