Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to print the following febonnaci series. 0 1 1 2 3 5 8 13 21 34 upto n times

Java Code Example — Series Programs

ADVERTISEMENT

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

  1. Initialize integers: x = -1, y = 1, and z.
  2. Prompt the user for the number of terms n.
  3. Start a for loop from 1 to n.
  4. Calculate the next term z = x + y.
  5. Print z.
  6. Shift the values: assign y to x, and z to y.
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 x to -1 and y to 1.
  • In the first iteration, z = (-1) + 1 = 0. Then x becomes 1 and y becomes 0.
  • In the second iteration, z = 1 + 0 = 1. This successfully bootstraps the standard 0, 1, 1 sequence without needing extra if conditions.

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 = z before x = y, both variables end up holding the new value.
ADVERTISEMENT