129. JAVA Program to find the Fibonacci series of a given number using recursion.
How does this program work?
- This program is used to find the fibonacci series of a given number using recursion in java.
- Fibonacci series means the previous two elements are added to get the next element starting with 0 and 1.
- First we initializing first and second number as 0 and 1, and print them.
- The third number will be the sum of the first two numbers by using loop.
- By using recursion method we can find the fibonacci series of a given number.
Here is the code
//To find the Fibonacci series of a given number using recursion
import java.util.Scanner;public class series
{
public static void main(String args[] )
{
System.out.println("Enter number: " );
int number = new Scanner(System.in).nextInt();
System.out.println("Fibonacci series upto "+ number +" numbers : ");
for ( int i=1; i<=number; i++ )
{
System.out.print(fibonacci2(i) +" " );
}
}
public static int fibonacci(int number )
{
if ( number == 1 || number == 2 )
{
return 1;
}//tail recursion
return fibonacci(number-1) + fibonacci(number -2);}
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 number is sum of previous two Fibonacci number
fibonacci = fibo1 + fibo2;fibo1 = fibo2;
fibo2 = fibonacci;
}
//Fibonacci number
return fibonacci;
}}