for Statement
A for
statement creates loops in which a counter variable is automatically maintained. The for statement lets you set an initial value for the counter variable, the amount to be added to the counter variable on each execution of the loop, and the condition that’s evaluated to determine when the loop should end.
A for statement follows this basic format:
for (initialization-expression; test-expression; count-expression)
statement;
The three expressions in the parentheses following the keyword for control how the for loop works:
The initialization-expression
is executed before the loop begins. This expression initializes the counter variable. If you haven’t declared the counter variable before the for statement, you can declare it here.
The test-expression
is evaluated each time the loop is executed to determine whether the loop should keep looping. This expression tests the counter variable to make sure that it’s still less than or equal to the value you want to count to. The loop keeps executing as long as this expression evaluates to true. When the test expression evaluates to false, the loop ends.
The count-expression
is evaluated each time the loop executes. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access