C++ While Loop: Complete Guide
The while loop in C++ is used to repeatedly execute a block of code as long as a specified condition is true. The basic syntax of a while loop is as follows:
while (condition)
{
// 循环体代码
}
The condition specified in the boolean expression is used to determine the termination condition of the loop. As long as the condition is true, the code within the loop will be executed repeatedly.
Here is an example using a while loop that will print numbers from 1 to 10:
int i = 1; // 初始化计数器
while (i <= 10) // 循环条件
{
cout << i << " "; // 输出当前数字
i++; // 更新计数器
}
This code will output: 1 2 3 4 5 6 7 8 9 10. The counter i is incremented with each iteration in the loop. The loop terminates when the value of counter i is greater than 10.
Please remember, when using a while loop, make sure that the code inside the loop can change the loop condition, otherwise it may result in an infinite loop. In the example above, the value of i is incremented with each loop iteration, eventually causing the loop condition to become false and the loop to end.