Write a recursive and non recursive program in c to display the Fibonacci sequence.
/* Write a recursive and non recursive program to display the Fibonacci sequence*/
#include<stdio.h>
int rfib(int n)
{
if(n == 1)
return 0;
else if(n == 2)
return 1;
else
{
return rfib(n - 1) + rfib(n - 2);
}
}
int main()
{
int n1=0,n2=1,n3,i,number;
printf("Enter the number of elements or terms:");
scanf("%d",&number);
printf("\n ***fibonacci sequence without recursion:");
printf("\n%d %d",n1,n2);//printing 0 and 1
for(i=2;i<number;i++ )//loop starts from 2 because 0 and 1 are already printed
{
n3=n1+n2;
printf(" %d",n3);
n1=n2;
n2=n3;
}
printf("\n \n***fibonacci sequence with recursion:");
for(int i=1;i<=number;i++)
{
printf("\n %d \n",rfib(i));
}
return 0;
}
Comments
Post a Comment