# Thread: help me, factorial in C recursive

1. ## help me, factorial in C recursive

can you guys please tell me why this wont do the factorial math!!

Code:
```#include <stdio.h>
#include <conio.h>
#include <ctype.h>

main()
{
int n, total, i;
total = 1;
printf("Enter a natural number: ");
scanf ("%d", &n);

while (n < 0)
{
printf ("Error Please Re-Enter Your Natural Number");
scanf ("%d", &n);
}
i = 1;

for (n > 0; i = n; i++)
{
total = total * i;
}
printf ("%d", total);

fflush(stdin);
getch();
return 0;
}```

2. The mistake is in the following line:
Code:
`for (n > 0; i = n; i++)`
Try to think about it: you should make i count from 1 onwards, and stop when it reaches n.

3. fflush(stdin) is undefined.
getch() is nonportable.
main() returns int.
The factorial is not recursively calculated.
Do you actually know what recursion means?

4. Do you actually know what recursion means?
See my signature.

In addition to what others have stated (especially the lack of recursion, and the broken for()):
Indent your code. This will make it so much easier to read - for you and the board.

For for():
The first is a statement that occurs at the start of the loop.
The second part is the condition that must hold true before each iteration.
The third part is a statement to run after each iteration. So:
Code:
`for(x = 0; x < 10; ++x)`
Runs for ten iterations. (x starts at zero, the loop runs while x is less than 10, and after each iteration, x is incremented) This is equivalent to:
Code:
```x = 0;
while(x < 10)
{
statements...
++x;
}```

Popular pages Recent additions