A for
loop is a type of loop construct that allows a block of code to be executed repeatedly for a fixed number of times. The
for
loop is typically used when the number of iterations is known in advance and consists of three parts:
- The initialization statement is executed once at the beginning of the loop. It is used to initialize the loop counter or any other variables
that may be used in the loop.
- The loop condition is evaluated at the beginning of each iteration, and if it is
true
, the code inside the loop is executed.
- The update statement is executed at the end of each iteration and is used to update the loop counter or any other variables that may be used in
the loop.
for (initialization; termination; increment) { /*...*/ }
All three statements are optional. However, when the initialization and update statements are not used, it can be unclear to the reader what the
loop counter is and how it is being updated. This can make the code harder to understand and maintain.