C Program for Fibonacci Series
The following code prints first n fibonacci numbers 0,1,1,2,3... Also it finds the nth term of a Fibonacci series using recursive function.
The algorithm for Fibonacci series is start from first number 0 then second number 1, now add previous two numbers to finds the next number in the series which is 1, following the same procedure again the next term is 2 and so on.
The algorithm for Fibonacci series is start from first number 0 then second number 1, now add previous two numbers to finds the next number in the series which is 1, following the same procedure again the next term is 2 and so on.
C Program for Fibonacci Series
/* Aim: Write a prgram to display first n fibonacci numbers (0,1,1,2,3,.... */
#include<stdio.h>
int main()
{
int i,n,n1=0,n2=1,an;
printf("\n Enter the number of terms you want to print:- ");
scanf("%d",&n);
printf("Fibonacci Sequence: ");
for (i=1;i<=n;++i)
{
printf("%d\t",n1);
an=n1+n2;
n1=n2;
n2=an;
}
}
/* Output of above code:-
Enter the number of terms you want to print: 10
Fibonacci Sequence: 0 1 1 2 3 5 8 13 21 34
*/
C program for Fibonacci Series using recursion
The following code finds nthe term of Fibonacci sequence using recursive function./* Aim: Write a recurssive function to find nth fibonacci number */
#include<stdio.h>
int fibonacci(int n); // Function Prototype
int main()
{
int n,i;
printf("\n Which term do you want to find:- ");
scanf("%d",&n);
printf("\n %d term of fibonacci sequence is %d \n \n",n,fibonacci(n));
return 0;
}
// fibonacci Function
int fibonacci(int n)
{
if (n==1 || n== 2)
return 1;
else
return( fibonacci(n-2) + fibonacci(n-1));
}
/* Output of above code:-
Which term do you want to find:- 4
4 term of fibonacci sequence is 3
*/