Sudhanshu Goyal - 1 year ago 53

C Question

I am trying to calculate factorial using recursion but my program is returning wrong value. I am unable to understand the recursion functionality. Please help me in understanding how recursion works. My code is as follows:

`#include <stdio.h>`

#include <math.h>

int main()

{

//code

int T,N,sol;

scanf("%d\n",&T);

while(T--) {

scanf("%d\n",&N);

sol=fact(N);

printf("%d\n",sol);

}

return 0;

}

int fact(int n)

{

int value;

while(n>0) {

value=n*fact(n-1);

n=n-1;

}

return value;

}

Answer Source

Replace your fact function with this one:

```
int fact(int n)
{
int value = 1;
if(n>0)
{
value=n*fact(n-1);
}
return value;
}
```