Here you are going to learn how to write a Fibonacci series in C program in different ways like using recursion, function, using loops like for and while loop.
Fibonacci series is a sequence followed by 0 and 1. The Fibonacci series is formed by adding the previous two numbers gives the next number in the series.
How it works:
First previous number + second previous number = result
Example 1: 0+1=1
Here 0 is the first previous number and 1 is the second previous number. Then the result is 0, 1, 1.
Example 2:
Up to now, the Fibonacci series formed is 0, 1, 1. Then according to formula adding the previous two values obtain the next value in the series.
1+1=2
Here both the previous values are 1 and 1. So the result is 2.
Example 3:
Fibonacci series formed is 0,1, 1, 2
Now 1+2=3
Next 2+3=5
Next 3+5=8 Upto now the series is 0, 1, 1, 2, 3, 5, 8
Fibonacci Series in C Program:
#include<stdio.h>
void main()
{
int h=0,h1=1,h2,j,k;
printf("Enter values:");
scanf("%d",&k);
printf("\n%d %d",h,h1);
for(j=2;j<k;++j)
{
h2=h+h1;
printf(" %d",h2);
h=h1;
h1=h2;
}
}
Output:
Enter values:8
0 1 1 2 3 5 8 13