Write a program to print Fibonacci series in java ?

What is Fibonacci series

Fibonacci series is a sequence of natural numbers and the next number is the sum of the two previous numbers, such as fn = fn-1 + fn-2. The first two numbers in the Fibonacci series are always 1,1. Below is the example

1 1 2 3 5 8 13 21 34 55 89 144 

Fibonacci Series – Using For loop

class FibonacciSeries {
public static void main(String args[]) {
   int seriesNum1 = 0;
   int seriesNum2 = 1;
   int number = 15;//Given number
   System.out.print(seriesNum2 + " ");
   int seriesNum3 = 0;

   for (int i = 1; i < number; i++) {
      // loop starts from 1 index because 1 element are already printed
      seriesNum3 = seriesNum1 + seriesNum2;
      System.out.print(seriesNum3 + " ");
      seriesNum1 = seriesNum2;
      seriesNum2 = seriesNum3;
   }
  }
}

Output

1 1 2 3 5 8 13 21 34 55 89 144 233 377 610

Fibonacci Series – Using While Loop

public class FibonacciSeries {
public static void main(String[] args) {

   int number = 15; //Given number
   int seriesNum1 = 1; 
   int seriesNum2 = 1; 
   int i = 0; 
  while (i < number) { 
    System.out.print(seriesNum1 + " ");
    int sum = seriesNum1 + seriesNum2;
    seriesNum1 = seriesNum2; 
    seriesNum2 = sum; 
    i = i + 1; 
  }
 }

}

Output

1 1 2 3 5 8 13 21 34 55 89 144 233 377 610

Display Fibonacci Series numbers which is less than a given number

public class FibonacciSeries {

  public static void main(String[] args) {
    int number = 150; //print number less than 150
    int seriesNum1 = 1; 
    int seriesNum2 = 1; 

    while (seriesNum1 <= number) { 
    
    System.out.print(seriesNum1 + " "); 
    int sum = seriesNum1 + seriesNum2; 
    seriesNum1 = seriesNum2; 
    seriesNum2 = sum; 
  }
 }
}

Output

1 1 2 3 5 8 13 21 34 55 89 144

Fibonacci Series – Using Recursion

Recursion is the process of repeating elements in a self-similar way. In programming languages, if a program allows you to call a function within the same function, then is called a recursive call of the function

class FibonacciSeries {
static int seriesNum1 = 0;
static int seriesNum2 = 1;
static int seriesNum = 0;
public static void displayFibonacci(int count) {
if (count > 0) {
seriesNum = seriesNum1 + seriesNum2;
seriesNum1 = seriesNum2;
seriesNum2 = seriesNum;
System.out.print(seriesNum+" ");
displayFibonacci(count - 1);
}
}
public static void main(String args[]) {
int number = 15; //Given Number
System.out.print(seriesNum2 + " ");// printing 1
displayFibonacci(number - 1);// n-1 because 1 numbers are already printed
}
}

Output

1 1 2 3 5 8 13 21 34 55 89 144 233 377 610