C++ For Loop

C++ For Loop

When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop.

Syntax

for (statement 1; statement 2; statement 3) {
  // code block to be executed
}

Example

Example

for (int i = 0; i < 5; i++) {
  cout << i << "\n";
}
* `int i = 0` initializes the loop counter. * `i < 5` ensures the loop runs as long as `i` is less than 5. * `i++` increments the counter after each iteration.

For loops are the best choice for iterating over arrays and strict counting tasks.


Exercise

?

In a for loop syntax for (statement 1; statement 2; statement 3), what does statement 2 typically define?