Question
Program to print Fibonacci numbers from 1 to N using recursion without using a third variable.
Enter N:
13
Fibonacci numbers from 1 to 13:
1
1
2
3
5
8
13
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
import java.util.Scanner;
public class fibonacciUsingRecursion
{
int n=0;
public void Printfibonacci(int a,int b)
{
if(b>n)
{
return;
}
else
{
System.out.println(b);
b=a+b;
a=b-a;
Printfibonacci(a,b);
}
}
public static void main()
{
fibonacciUsingRecursion ob1=new fibonacciUsingRecursion();
Scanner sc=new Scanner(System.in);
System.out.println("Enter N:");
ob1.n=sc.nextInt();
System.out.println("Fibonacci numbers from 1 to "+ob1.n+":");
ob1.Printfibonacci(0,1);
}
}