C++ For Loop: Complete Guide
The for loop statement in C++ can be used in the following format:
for (初始化; 条件判断; 增量) {
// 循环体语句
}
The initialization part is executed once before the loop starts, to initialize the loop control variable; the condition check part is executed before each loop starts, to determine whether to continue the loop; the increment part is executed after each loop ends, to update the loop control variable.
Here is an example of using a for loop to output numbers 1 to 10:
#include <iostream>
int main() {
for (int i = 1; i <= 10; i++) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
The output is: 1 2 3 4 5 6 7 8 9 10.