A for loop is a type of loop that executes a block of code repeatedly until a condition is false. The for loop is different from the while loop in that the condition is evaluated before the loop body is executed for the first time.
The syntax for a for loop is as follows:
for (initialization; condition; increment) {
// loop body
}
The initialization statement is executed once before the loop starts. The condition statement is evaluated before each iteration of the loop. If the condition is true, the loop body is executed. If the condition is false, the loop terminates. Theincrement statement is executed after each iteration of the loop.
Example
The following example shows a simple for loop:
for (int i = 0; i < 10; i++) {
std::cout << i << std::endl;
}
Output:
0
1
2
3
4
5
6
7
8
9
Nested for loops
You can also nest for loops, which means that you can have one for loop inside another for loop. This can be useful for performing complex tasks, such as iterating over a two-dimensional array.
The following example shows a nested for loop:
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
std::cout << i << ", " << j << std::endl;
}
}
Output:
0, 0
0, 1
0, 2
...
9, 9
Conclusion
For loops are a powerful tool that can be used to perform repetitive tasks in your C++ code. By using for loops, you can simplify your code and make it more efficient.