The numbers in the Fibonacci sequence follow the following pattern: every number after the first two is the sum of the two preceding ones. First few numbers in the Fibonacci series are as follows: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89. The 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.
In this blog, I am posting codes in C to generate the Fibonacci numbers with recursion and without recursion. The codes do not have all possible checks e.g. if n <0. These are just templates and can be modified to satisfy all cases.
C Program without recursion
#include<stdio.h>
int fibo(int a[], int k){
return a[k-2]+a[k-1];
}
int main(){
/* this program will print fibonacci series */
int tot;
printf("How many numbers you want in fibonacci series:");
scanf("%d",&tot);
int results[tot]; //to store values of fibonacci series
results[0]=0;
results[1]=1;
for(int i=2;i<tot;i++)
results[i]=fibo(results,i);
printf ("First %d elements of fibonacci series are:", tot);
for (int j=0;j<tot;j++)
printf("%d ",results[j]);
printf("\n");
return 0;
}
$ ./tfunc.out
How many numbers you want in Fibonacci series:20
First 20 elements of Fibonacci series are:0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
C Program with recursion
#include<stdio.h>
int fibo(int n){
if (n==0)
return 0;
else if(n==1)
return 1;
else
return(fibo(n-1) + fibo(n-2));
}
int main(){
/* this program will print fibonacci series */
int n;
printf("How many numbers you want in fibonacci series:");
scanf("%d",&n);
printf("First %d elements in fibonacci series are:",n);
for (int i=0;i<n;i++)
printf("%d ",fibo(i));
printf("\n");
return 0;
}
$ ./recur.out
How many numbers you want in Fibonacci series:20
First 20 elements in Fibonacci series are:0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
Thanks for the code.
It works