Wednesday, February 11, 2015

C C Program for Fibonacci Series Using Recursion

Series 0, 1, 1, 2, 3, 5, 8, 13, 21 . . . . . . . is a Fibonacci series. In Fibonacci series, each term is the sum of the two preceding terms. The C and C++ program for Fibonacci series is given below.

C Program


#include<stdio.h>

int fibonacci(int n)
{
if((n==1)||(n==0))
{
return(n);
}
else
{
return(fibonacci(n-1)+fibonacci(n-2));
}
}

int main()
{
int n,i=0;
printf("Input the number of terms for Fibonacci Series:");
scanf("%d",&n);
printf("
Fibonnaci Series is as follows
");
while(i<n)
{
printf("%d ",fibonacci(i));
i++;
}

return 0;
}

C++ Program


#include<iostream>

using namespace std;

int fibonacci(int n)
{
if((n==1)||(n==0))
{
return(n);
}
else
{
return(fibonacci(n-1)+fibonacci(n-2));
}
}

int main()
{
int n,i=0;
cout<<"Input the number of terms for Fibonacci Series:";
cin>>n;
cout<<"
Fibonnaci Series is as follows
";

while(i<n)
{
cout<<" "<<fibonacci(i);
i++;
}

return 0;
}

C/C++ Program for Fibonacci Series Using Recursion