How does the following code work?

I have problem understanding the following code calculating the factorial numbers smaller than a certain limit:

1
2
3
4
5
6
7
8
9
int main()
{ long bound;
cout << "Enter a positive integer: "; cin >> bound;
cout << "Factorial numbers that are <= " << bound << ":\n1, 1"; 
long f=1;
for (int i=2; f <= bound; i++)
{ f *= i;
cout << ", " << f; }
}

The output for the positive integer: 1000000 is 1,1,2,6,24,120,720,5040,40320,362880

I know that the first two numbers in the output come from line 4. But how about 2? Why do I get three instead of 2?

1) f=1 and <100000
2) i needs to be incremented
3) f=f(i+1) => f=1(2+1)=3
Review for loops.
for (init; condition; increment) statement; is roughly equivalent to
init; while (condition) { statement; increment; }
You should be able to find more information with a few seconds of research.

That is, i is incremented after the loop body executes, immediately before the condition is tested for the second time.
Last edited on
Thanks a lot.
Topic archived. No new replies allowed.