C++ For Loop
Repeating code with for loops.
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
}
- Statement 1 is executed (one time) before the execution of the code block. It is typically used to initialize the loop variable.
- Statement 2 defines the condition for executing the code block. If true, the loop executes. If false, the loop ends.
- Statement 3 is executed (every time) after the code block has been executed. It is typically used to increment or decrement the loop variable.
Foreach Loop
C++ also has a "range-based for loop" (often called for-each), which is used exclusively to loop through elements in an array or other data sets. It is safer and easier to read.