Hello,
I have been working on a program to calculate the factorial of numbers.
Part of my code is copied and modified from the FAQ about validating numbers in user input.
I have encountered a problem with the for loop that I am using near the end of my code. No matter what I do, it seems that my loop only does the multiplication of b = a*(a-1) and then prints. For example, inputting 5 will result in a print of 20, but the factorial is 120.
I would appreciate any advice, which may help me solve the problem!
Code:
int main(void)
{
char buf[BUFSIZ];
char *p;
long int a;
long int b;
long int i;
printf ("Enter a number to be factorialized: ");
if (fgets(buf, sizeof(buf), stdin) != NULL) {
a = strtol(buf, &p, 10);
if (buf[0] != '\n' && (*p == '\n' || *p == '\0'))
printf ("Valid number of %ld entered.\n", a);
else {
printf ("The number was %d, followed by the invalid character(s): %s\n", a, p);
getch();
return 0;
}
if (a < 0) {
printf("Error: Value is less than zero!");
getch();
return 0;
}
if (a > 0) {
for(i=1;i<a;i++){
b=a*i; }
printf("The factorial value, %ld!, is: %ld", a, b);
getch();
return 0;}
}}