# Thread: Problem with a for loop

1. ## Problem with a for loop

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;}
}}```

2. No matter what I do, it seems that my loop only does the multiplication of b = a*(a-1) and then prints
That's because the value of 'b' is overwritten with each iteration of the loop. "Run" the for loop by hand on paper, and you'll see what your code is actually doing.

Also, the logic for that loop is not quite correct, but let's look at one thing at a time.

3. I think I found a mistake. Shouldn't the loop end with i++; so i+1 is used every time the loop is run, until i < a, although that didn't solve the problem, so I'll just try to figure out what the loop does in reality.

4. My apologies if I've missed the edit option for my previous post to prevent double posting.
What I've come up with is the following:
Code:
``` if (a > 0) {
for(i=1;i<=a;i++)
a=a*i;
}```
Its still not perfect, so I may be wrong about the aforementioned code. When I input 5, it outputs the result as -1899959296, so obviously something is wrong. Could it be something wrong with the data types I am using?

5. Code:
``` if (a > 0) {
for(i=1;i<=a;i++)
a=a*i;
}```
What happens to your variable "a"? Will "i" ever be able to be greater than "a" before "a" overflows?

Bye, Andreas

6. Oh, damn! Of course, a will gradually increase much higher than i, thus running the code to infinity, if that was possible.
Fixed it now and the program works (with b = 1 in the beginning of my code):
Code:
```    if (a > 0) {
for(i=1;i<=a;i++){
b=b*i;
}
printf("The factorial value of input is: %ld", b);```