Java Program for Fibonacci Series
The Fibonacci series is a sequence where each number is the sum of the two preceding numbers.
It usually starts with 0 and 1.
1. Understanding the Problem
Generate Fibonacci series up to a given number of terms.
Terms: 5 → 0 1 1 2 3 Terms: 7 → 0 1 1 2 3 5 8
2. Using Basic Loop
Java
import java.util.Scanner;
public class FibonacciSeries {
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;
}
}
}
3. Optimized Approach (Using Recursion)
Java
import java.util.Scanner;
public class FibonacciRecursive {
static int fib(int n) {
if (n <= 1)
return n;
return fib(n - 1) + fib(n - 2);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of terms: ");
int n = sc.nextInt();
System.out.print("Fibonacci Series: ");
for (int i = 0; i < n; i++) {
System.out.print(fib(i) + " ");
}
}
}
4. Common Mistakes
1. Incorrect initialization of first two numbers.
2. Using recursion without understanding performance impact.
3. Printing wrong number of terms.
4. Not handling n = 0 or n = 1 properly.
5. Applications
1. Used in algorithm design and dynamic programming.
2. Appears in nature (e.g., leaf arrangement, spirals).
3. Common interview and beginner programming problem.
Conclusion
Fibonacci series is a classic example to understand loops and recursion.
Iterative methods are more efficient than recursion for large inputs.
Codecrown