Java Program for Fibonacci Series


In this post, we will learn, How to write a program to display Fibonacci Series based on given user input.

Before moving to the programming part, Let's try to understand, What is Fibonacci Series? 


Fibonacci Series- This is the number of sequences in which the series starts with 0,1 and the next number is found by adding up the two numbers before it.


Ex:- 0,1,1,2,3,5,8,13,21.........


Code-


public class Fibonacci {

  public static void main(String[] args) {

    int n = 10, t1 = 0, t2 = 1;

    System.out.print("First " + n + " terms: ");


    for (int i = 1; i <= n; ++i) {

      System.out.print(t1 + ",");


      int sum = t1 + t2;

      t1 = t2;

      t2 = sum;

    }

  }

}



Output- 


First 10 terms: 0,1,1,2,3,5,8,13,21,34,


Explanation-

This program uses a for loop to iterate from 1 to the number of terms specified by the variable n. The loop initializes two variables, t1 and t2, to 0 and 1 respectively. These variables are used to keep track of the previous two terms in the series.

In each iteration of the loop, the current term in the series is computed as the sum of the previous two terms (t1 + t2) and the value is printed out. The values of t1 and t2 are then updated for the next iteration.

Print Fibonacci Series Using Recursive Function

Code- 

public class Fibonacci {


  static int n1 = 0, n2 = 1, n3 = 0;


  static void printFibonacci(int count) {

    if (count > 0) {

      n3 = n1 + n2;

      n1 = n2;

      n2 = n3;

      System.out.print(" " + n3);

      printFibonacci(count - 1);

    }

  }


  public static void main(String args[]) {

    int count = 10;

    System.out.print(n1 + " " + n2);//printing 0 and 1    

    printFibonacci(count - 2);//n-2 because 2 numbers are already printed   

  }

}


Explanations-


The program defines a static method called printFibonacci() which takes an integer argument representing the number of terms to be printed. The method uses a base case of count > 0 to stop the recursion when the specified number of terms have been printed.


In each recursive call, the next term in the series (n3) is computed as the sum of the previous two terms (n1 + n2) and the value is printed out. Then the values of n1 and n2 are updated for the next recursive call.


The main method sets the number of terms to be printed to 10 and prints the first two terms (0 and 1) before calling the printFibonacci() method.


Hope this program helpful for you, Please put your valuable comment and share with your friends-------


Post a Comment

Previous Post Next Post