Fibonacci series is series of natural number where next number is equivalent to the sum of previous two number e.g. fn = fn-1 + fn-2. The first two numbers of Fibonacci series is always 0, 1.
In fibonacci series, next number is the sum of previous two numbers for example 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 etc.
import java.util.*;
class fibo
{
int fib(int n)
{
int a=0,b=1;
if (n <= 1)
return a;
else if(n==2)
return b;
else
return fib(n-1) + fib(n-2);
}
void genSeries()
{ Scanner sc=new Scanner(System.in);
int n ,c;
System.out.println("Enter the limit:");
n=sc.nextInt();
System.out.println("The Fibonacci series is:");
for(int i=1;i<=n;i++)
{
c=fib(i);
System.out.print(c +" ");
}
}
public static void main (String args[])
{
fibo f=new fibo();
f.genSeries();
}
}
Output:
Enter the limit:
6
The Fibonacci series is:
0 1 1 2 3 5