Learn about Fibonacci Series in C in the below code example. Also refer the comments in the code snippet to get a detailed view about whatโs actually happening.
Contents
Fibonacci Series in C:
Fibonacci series are : 0,1,1,2,3,5,8,13,โฆโฆโฆetc. The coming number is defined by sum of previous two numbers. These series are caught using two ways
- Fibonacci series using Recursion(using user defined function).
- Fibonacci series without Recursion.
Method 1:
Recursion involves function call. Here is the example of program to print fibonacci series.
#include<stdio.h>
void fibonacci(int n)
{
static int a=0,b=1,c;
if(n>0)
{
c=a+b;
a=b;
b=c;
printf("%d ",c);
fibonacci(n-1);//recursion call
}
}
int main()
{
int n;
printf("Enter number of elements:");
scanf("%d",&n);
printf("%d %d ",0,1);//1st and 2nd element of fibonacci series
fibonacci(n-2);//fibonacci series of remaining
return 0;
}
Enter number of elements:10
0 1 1 2 3 5 8 13 21 34
Method 2:
Fibonacci series without recursion is done using for loops. Here is example of program to print fibonacci series without recursion.
#include<stdio.h>
int main()
{
int n,a=0,b=1,c;
printf("Enter number of elements:");
scanf("%d",&n);
printf("%d %d",a,b);//1st and 2nd elements of fibonacci
for(int i=0;i<n-2;i++)
{
c=a+b;
a=b;
b=c;
printf(" %d",c);
}
}
Enter number of elements:10
0 1 1 2 3 5 8 13 21 34
Hope above code works for you and Refer the below Related Codes to gain more insights. Happy coding and come back again.
Also Read: