C Loops: for, while, do-while Guide
In C language, loop statements can be used to repeatedly execute specific code blocks. There are three main loop statements in C language: for loop, while loop, and do-while loop.
- For loop: The for loop statement consists of three parts: initialization expression, loop condition, and loop iteration expression. The basic syntax of a for loop is as follows:
for (初始化表达式; 循环条件; 循环迭代表达式) {
// 循环体代码块
}
- While loop: A while loop consists of only one looping condition. The code block within the loop will continue to execute as long as the condition remains true. The basic syntax of a while loop is as follows:
while (循环条件) {
// 循环体代码块
}
- The do-while loop is similar to the while loop, but the main difference is that the loop body will be executed at least once because the loop condition is evaluated after the loop body. The basic syntax of the do-while loop is as follows:
do {
// 循环体代码块
} while (循环条件);
By using these loop statements, it is easy to repeat the execution of code blocks, choose the appropriate loop statement according to specific needs.