Following code will help you understand:
import java.util.*;
public class Fibonacci {
public static void main(String[] nt)
{ int a=0,b=1,next;
Scanner in=new Scanner(System.in);
{ System.out.println("Enter Number of Terms");
int n=in.nextInt();
if(n<1)
{
System.out.println("Invalid No of Terms !! Please Try Again");
}
else if(n==1)
{ System.out.println("Terms are");
System.out.println(a);
}
else
{ System.out.println("Terms are");
System.out.print(a+" "+b+" ");
for(int i=3;i<=n;i++)
{
next=a+b;
System.out.print(next+" ");
a=b;b=next;
}
System.out.println();
}
}
}
}
Output:
import java.util.*;
public class Fibonacci {
public static void main(String[] nt)
{ int a=0,b=1,next;
Scanner in=new Scanner(System.in);
{ System.out.println("Enter Number of Terms");
int n=in.nextInt();
if(n<1)
{
System.out.println("Invalid No of Terms !! Please Try Again");
}
else if(n==1)
{ System.out.println("Terms are");
System.out.println(a);
}
else
{ System.out.println("Terms are");
System.out.print(a+" "+b+" ");
for(int i=3;i<=n;i++)
{
next=a+b;
System.out.print(next+" ");
a=b;b=next;
}
System.out.println();
}
}
}
}
Output: