Java Program to print the following febonnaci series. 0 1 1 2 3 5 8 13 21 34 upto n times
Objective
Write a Java program to generate the Fibonacci series up to N terms.
Algorithm / Approach
- Initialize integers:
x = -1,y = 1, andz. - Prompt the user for the number of terms
n. - Start a
forloop from 1 ton. - Calculate the next term
z = x + y. - Print
z. - Shift the values: assign
ytox, andztoy.
Test.java
import java.util.Scanner;
class Test {
public static void main(String[] a)
{
int x = -1, y = 1, z;
Scanner s=new Scanner(System.in);
System.out.print("Enter N: ");
int n = s.nextInt();
for(int i = 1; i<=n; i++) {
z = x+y;
System.out.print(z+" ");
x = y;
y = z;
}
}
}
Expected Output
Enter N: 10 0 1 1 2 3 5 8 13 21 34
Explanation of the Program
- The Fibonacci series is a sequence where each number is the sum of the two preceding ones, usually starting with 0 and 1.
- The clever trick used here initializes
xto -1 andyto 1. - In the first iteration,
z = (-1) + 1 = 0. Thenxbecomes 1 andybecomes 0. - In the second iteration,
z = 1 + 0 = 1. This successfully bootstraps the standard 0, 1, 1 sequence without needing extraifconditions.
Complexity
Time Complexity
O(n) - Calculates one Fibonacci term per loop iteration.
Space Complexity
O(1)
Common Mistakes
- Shifting the variables in the wrong order. If you assign
y = zbeforex = y, both variables end up holding the new value.