TL;DR
This
for (int j = 1; j <= n; ++j)
for (int k = 1; k <= j; ++k)
result[i++] = k;
is equivalent to below code (formatted with curly braces), which increments i
inside the two for-loop:
for (int j = 1; j <= n; ++j) {
for (int k = 1; k <= j; ++k) {
result[i++] = k;
}
}
And this
for (int j = 1; j <= n; ++j)
for (int k = 1; k <= j; ++k)
result[i] = k;
i++;
is equivalent to this code (formatted with curly braces), which increments i
after the two for-loop are executed:
for (int j = 1; j <= n; ++j) {
for (int k = 1; k <= j; ++k) {
result[i] = k;
}
}
i++;
Basically, when curly braces are not used, instructions such as for
, while
, if
, etc, interpret only the next line as the code block to be executed as part of its statement.
In your case you replaced result[i++] = k;
(one line) for (two lines)
result[i] = k;
i++
leaving, this way, the second line (i++
) out of the statement to be executed by the for. Following the same principle, the outer loop ignores the i++
sentence too.
When curly braces and code formatting are correctly used, this should never happen.
Long Story
This is the for
statement:
for ( [ForInit] ; [Expression] ; [ForUpdate] ) Statement
Where Statement
can be (among others) an ExpressionStatement
or a Block
.
The ExpressionStatement
you used by doing result[i++] = k;
was an Assignment
(two of them, actually: result[i] = k;
and i = i + 1
, but, in one line), which is:
LeftHandSide AssignmentOperator Expression
result[i] = k ; // leaving out the `++` operation for simplicity here
Now, when you changed to the second alternative, without using curly braces, the Statement
used by the for
is still the first line next to it
result[i] = k; // <-- this keeps being the `Statement` taken by the `for`
i++ // and this line is not considered as a statement to be used by the for anymore
But, if you would have used curly braces, this would have become a Block
statement in the form
{ [BlockStatements] }
Where BlockStatements
is
BlockStatement {BlockStatement}
And each BlockStatement
can be (among others) a Statement
. Thus you would have been able to put as many Assignment
s (remember this is a Statement
) as you wish to be executed by the for
s statements.
Further readings: