Home > DeveloperSection > Blogs > Fibonacci series Using Recursion

#### Fibonacci series Using Recursion

Ratings:
0 Comment(s)
2499  View(s)
Rate this:

Fibonacci series Using Recursion

In this blog I am provide you the complete code for generating Fibonacci series using java.

import java.util.Scanner;

import java.io.*;

public class FibonacciCalculator {

public static void main(String args[]) {

//input to print Fibonacci series upto how many numbers

System.out.println("Enter number upto which Fibonacci series to print: ");

int number = new Scanner(System.in).nextInt();

System.out.println("Fibonacci series upto " + number +" numbers : ");

//printing Fibonacci series upto number

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

System.out.print(fibonacci2(i) +" ");

}

}

/*

* Java program for Fibonacci number using recursion.

* This program uses tail recursion to calculate Fibonacci number for a given number

* @return Fibonacci number

*/

public static int fibonacci(int number){

if(number == 1 || number == 2){

return 1;

}

return fibonacci(number-1) + fibonacci(number -2); //tail recursion

}

/*     * Java program to calculate Fibonacci number using loop or Iteration.

* @return Fibonacci number

*/

public static int fibonacci2(int number){

if(number == 1 || number == 2){

return 1;

}

int fibo1=1, fibo2=1, fibonacci=1;

for(int i= 3; i<= number; i++){

fibonacci = fibo1 + fibo2; //Fibonacci number is sum of previous two Fibonacci number

fibo1 = fibo2;

fibo2 = fibonacci;

}

return fibonacci; //Fibonacci number

}

}