I am required to print the fibonacci series using a recursive function
int fib(int n) where n is the number of elements in the series.I pass this through main.And i am not allowed to use any loops in main,such as
Code:
int b=0;
for(c=0;c<n;c++)
{
b=fib(n);
printf("%d",b);
}
I am supposed to print the elements of the series in the recurssive function itself.And i should print only the elements of the series and nothing else.I have tried a program and it works fine.But is there a much simpler code than this.Also,any tips for improving my coding style is abolutely welcome.This is my code
Code:
#include<stdio.h>
static int r=0;
int fib(int n);
int main(void)
{
int n=0;
printf("enter the number of elements");
scanf("%d",&n);
fib(n);
}
int fib(int n)
{
int p=0;
if(n<0)
{
printf("enter a number greater than 0");
return -1;
}
if(n==1)
{
if(r==0)
{
printf("%d\n",0);
r++;
return 0;
}
else
{
return 0;
}
}
else if(n==2)
{
if(r==1)
{
printf("%d\n",1);
r++;
return 1;
}
else
{
return 1;
}
}
else if(n%2==1)
{
if(n>r)
{
p=fib(n-2)+fib(n-1);
printf("%d\n",p);
r=n;
return p;
}
else
{
p=fib(n-2)+fib(n-1);
return p;
}
}
else if(n%2==0)
{
if(n>r)
{
p=fib(n-1)+fib(n-2);
printf("%d\n",p);
r=n;
return p;
}
else
{
p=fib(n-1)+fib(n-2);
return p;
}
}
return 0;
}
Thanks.