Java Examples

java program fibonacci using recursion

FibonacciUsingRecursion.java

import java.util.Scanner;

/**
 * @author Candid Java
 */

public class FibonacciUsingRecursion {
 static Scanner scan;

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

 static void printFibonacciSeries(int count) {
  if (count > 0) {
   n3 = n1 + n2;
   n1 = n2;
   n2 = n3;
   System.out.print(" " + n3);
   printFibonacciSeries(count - 1);
  }
 }

 public static void main(String args[]) {
  Scanner sc = new Scanner(System.in);
  int count;
  System.out.println("Enter the limit:");
  count = sc.nextInt(); // getting the max limit of count
  System.out.print(n1 + " " + n2); // printing 0 and 1
  printFibonacciSeries(count - 2); // count-2 because 2 numbers are already printed
  sc.close();
 }
}

Output

Enter the limit:20
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181