Fibonacci Series

The Fibonacci series is a series where the next term is the sum of the previous two terms. The first two terms of the Fibonacci sequence are 0 followed by 1.

Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34

public class Fibonacci {
  public static void main(String[] args) {
    int num = 5;

    int a=0,b=1,c=0;
    System.out.print("Fibonacci sequence: "+a+" "+b+" ");
    for(int i=2;i<num;i++){
      c = a+b;
      System.out.print(c+" ");
      a=b;
      b=c;
    }
  }
}
Fibonacci sequence: 0 1 1 2 3

num = 5

a = 0, b = 1

c = a+b = 0+1 = 1; a = 1,b = 1

c = a+b = 1+1 = 2; a = 1,b = 2

c = a+b = 1+2 = 3; a = 2,b = 3

sequence: 0 1 1 2 3

Fibonacci series using while loop:

public class Fibonacci {
  public static void main(String[] args) {
    int num = 5;

    int a=0,b=1,c=0,i=2;
    System.out.print("Fibonacci sequence: "+a+" "+b+" ");
    while(i<num){
      c = a+b;
      System.out.print(c+" ");
      a=b;
      b=c;
      i++;
    }
  }
}
Fibonacci sequence: 0 1 1 2 3

Fibonacci series up to a given number:

public class Fibonacci {
  public static void main(String[] args) {
    int num = 200;

    int a=0,b=1,c=0;
    System.out.print("Fibonacci sequence: "+a+" "+b+" ");
    while((a+b)<=num){
      c = a+b;
      System.out.print(c+" ");
      a = b;
      b = c;
    }
  }
}
Fibonacci sequence: 0 1 1 2 3 5 8 13 21 34 55 89 144

Fibonacci series using recursion:

Method 1:

public class Fibonacci {
  public static void main(String[] args) {
    int num = 5;
    System.out.print("Fibonacci sequence: ");
    for(int i=0;i<num;i++){
      System.out.print(fibonacci(i)+" ");
    }
  }

  static int fibonacci(int n){
    if(n < 2){
      return n;
    }
    return fibonacci(n-1) + fibonacci(n-2);
  } 
}
Fibonacci sequence: 0 1 1 2 3

Method 2:

public class Fibonacci {
  public static void main(String[] args) {
    int num = 5;

    int ans = fibonacci(num);
    System.out.println(ans);
  }

  static int fibonacci(int n){
    if(n < 2){
      return n;
    }

    return fibonacci(n-1) + fibonacci(n-2);
  } 
}
5
0
Subscribe to my newsletter

Read articles from Sirisha Challagiri directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sirisha Challagiri
Sirisha Challagiri