Question about for loop increment

This program, from Stephen Prata's C++ Primer Plus, outputs 2! = 2, which I know is correct. But when I try to follow the logic of the program, I do not understand why the i value is not incremented by the update expression i++ in line 7, for (int i = 2; i < ArSize; i++), from 2 to 3. But that would output the incorrect factorial of 3! = 2. Could somebody please enlighten me as to how the program is working in regard to that first update expression.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
const int ArSize = 4; 
int main()
{
	long long factorials[ArSize];
	factorials[1] = factorials[0] = 1LL;
	for (int i = 2; i < ArSize; i++)
		factorials[i] = i * factorials[i - 1];
	for (int i = 0; i < ArSize; i++)
		std::cout << i << "! = " << factorials[i] << std::endl;
	std::cin.get();
	return 0;
}


1
2
3
4
5
const int ArSize = 4;
for ( int i = 2; i < ArSize; i++ )
{
  // body
}

* The i is initially 2.
* On first try the condition (2<4) is true, the loop body is executed, and i is incremented to 3.
* On second try the condition (3<4) is still true, the loop body is executed, and i is incremented to 4.
* On third try the condition (4<4) is false, the loop is over. Execution continues from your line 9.


1
2
3
const int ArSize = 4; 
long long factorials[ArSize];
factorials[1] = factorials[0] = 1LL;

Initially:
factorials[0] == 1
factorials[1] == 1
factorials[2] is undefined
factorials[3] is undefined

The first execution of the loop's body evaluates this:
factorials[2] = 2 * factorials[1];
That updates factorials[2] to 2

The second execution of the loop's body evaluates this:
factorials[3] = 3 * factorials[2];
That updates factorials[3] to 6
I see. So in the program the first loop tests and executes all of the values until the array limit is reached and only then moves onto the second loop. That's correct, right? I thought that the program tested a single value, then moved onto the next for loop, hence how I came out with 3! = 2.
Thanks very much for your help.
Topic archived. No new replies allowed.