Question: what is problem in my c program to print the nth fibonacci number using recursion
Current behavior:
Desired behavior
Repl link:
#include<stdio.h>
int fib(int a,int b)
{
int c,d;
if(a==0)
return d;
if(b==0)
c=1;
d=b+c;
b=c;
c=d;
return fib(a-1,b);
}
int main()
{
int a;
printf("Enter the nth fibonacci number greater than 2:\n");
scanf("%d",&a);
printf("The %d element of fibonacci number is %d\n",a,fib(a-2,0));
return 0;
}
I won’t give you the direct answer but I’ll try to give a hint.
First of all, you should be indenting your code. I also feel like maybe some nicer variable names but I’ll leave that up to you…
When you return fib(a-1, b) you aren’t building up a value. You’re only returning whatever the next call to fib() returns but it will only ever return 0 or an undefined value of variable d. When you use recursion, you typically want to build up the answer along the return chain.
This isn’t the actual answer but for an example try return fib(a-1, b) + b
I’m not convinced you should be returning d if a==0 but maybe I’m wrong there.