Answer
Fibonacci Series in Java
Method 1: Iterative (Loop)
Java
public class FibonacciSeries {
public static void main(String[] args) {
int n = 10; // print first 10 Fibonacci numbers
int a = 0, b = 1;
System.out.print("Fibonacci Series: ");
for (int i = 0; i < n; i++) {
System.out.print(a + " ");
int next = a + b;
a = b;
b = next;
}
}
}
Output
CODE
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34
Method 2: While Loop
Java
int a = 0, b = 1, count = 0;
int n = 8;
System.out.print("Fibonacci: ");
while (count < n) {
System.out.print(a + " ");
int temp = a + b;
a = b;
b = temp;
count++;
}
// Output: Fibonacci: 0 1 1 2 3 5 8 13
Method 3: Recursive
Java
public static int fib(int n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}
// Print first 8 terms
for (int i = 0; i < 8; i++) {
System.out.print(fib(i) + " ");
}
// Output: 0 1 1 2 3 5 8 13
Note: Recursion is simple but inefficient O(2^n). Use iteration O(n) for large n.
Fibonacci Up to a Value (Not Count)
Java
int limit = 100;
int a = 0, b = 1;
System.out.print("Fibonacci up to " + limit + ": ");
while (a <= limit) {
System.out.print(a + " ");
int temp = a + b;
a = b;
b = temp;
}
// Output: Fibonacci up to 100: 0 1 1 2 3 5 8 13 21 34 55 89
Check if N is a Fibonacci Number
Java
public static boolean isFibonacci(int n) {
int a = 0, b = 1;
while (b < n) {
int temp = a + b; a = b; b = temp;
}
return b == n || n == 0;
}
System.out.println(isFibonacci(13)); // true
System.out.println(isFibonacci(14)); // false
