Fibonacci series in java: Algorithm and Programs

What is the Fibonacci series?

The Fibonacci series in java is a sequence 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.

The Fibonacci series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34….

Algorithm

The Fibonacci series starts with either 0 or 1 and the sum of every subsequent term is the sum of the previous two

Ex:-

n 0 1 2 3 4 5 6 7 8 9
Xn 0 1 1 2 3 5 8 13 21 34

 

It can be done in two ways

  • Fibonacci Series without using recursion
  • Fibonacci Series using recursion

Fibonacci series in java is a series of natural numbers the next term is the sum of the previous two terms like       fn = fn-1 + fn-2. The first two numbers of the Fibonacci series are always 0 and 1. in the Fibonacci series, we create a function called (Fibonacci()) to calculate the Fibonacci number and return the series. in the main function, we call the Fibonacci() and print the Fibonacci series in the consol

Using recursion

 

public class Fibonacci{
     public static int fibonacciRec(int n){
       if(n == 0){
       return 0;
       }
       if(n == 1 || n == 2){
       return 1;
       }
       return fibonacciRec(n-2) + fibonacciRec(n-1);
       }
public static void main(String args[]) {
   int maxNumber = 10;
   System.out.print("Fibonacci Series of "+maxNumber+" numbers: ");
   for(int i = 0; i < maxNumber; i++){
   System.out.print(fibonacci(i) +" ");
   }
  }
}

Fibonacci Series on User Input

import java.util.Scanner;
public class JavaExample {

    public static void main(String[] args) {

        int count, a = 0, b = 1;
        System.out.println("How may numbers you want in the series:");
        Scanner scanner = new Scanner(System.in);
        count = scanner.nextInt();
        scanner.close();
        System.out.print("Fibonacci Series of "+count+" numbers:");
         System.out.print(" numbers:");

        int i=1;
        while(i<=count)
        {
            System.out.print(c" ");
            int c;
            c = num1 + num2;
            a = b;
            b = c;
            i++;
        }
    }
}
How may numbers you want in the series:
6
Fibonacci Series of 6 
numbers:0 1 1 2 3 5

Without using recursion

 

public class Tester {
   public static void main(String args[]) {
       int a = 0, b = 1, c, i, max = 5;
       System.out.print(n1 + " " + n2);
       for (i = 2; i < max; ++i) {
          c = a + b;
          System.out.print(" " + n3);
          a = b;
          b = c;
       }
    }
 }

Output

0 1 1 2 3

 

Leave a Comment