Fibonacci Program In Java Using For Loop And Recurson

First two numbers in the Fibonacci sequence are either 1 and 1, or 0 and 1, depending on the chosen starting point of the sequence, and each subsequent number is the sum of the previous two.

import java.util.Scanner;

public class Fabo
{

public static void main(String[] args)
{

Scanner scn=new Scanner(System.in);
System.out.println("type limit to find fibonacci no.");
int n=scn.nextInt();
int n1=0;
int n2=1;
int n3=0;
for(int i=1;i<=n;i++)
{
n3=n1+n2;
n1=n2;
n2=n3;
System.out.print(n3 +"  ");

}


}

}

Recursion : 


public class FabonacciRec {

public static void main(String[] args) {

Scanner scn=new Scanner(System.in);
int n=scn.nextInt();

for(int i=1;i<=n;i++)
{
System.out.print(fab(i)+" ");
}


}
public static int fab(int n)
{
if(n==1||n==2)
{
return 1;
}
return fab(n-1)+fab(n-2);
}

}



Post a Comment

Previous Post Next Post