Understanding and details of loop statements (C language)

1.while

First let’s get to know the format

while(){//()里面填判断循坏条件的表达式,如果表达式为1则继续,为0则结束
        //括号里填需要执行的语句
}

detail:

The parentheses should have statements that change the loop conditions, or a break that can jump out of the program directly, otherwise an infinite loop is prone to occur.

Continues should be used with caution in while, as it may cause an infinite loop.

2.do while

Format

do{
             //执行语句
}while();    //()里面是循坏判断条件,表达式结果为1继续,为0结束循坏。

detail:

There must be a semicolon after it, otherwise a syntax error will be reported. This loop is the only program in the loop that will not be executed once regardless of the result of the expression. It must also be able to change the loop judgment conditions, or have a break to jump out of the program directly. Continues should also be used with caution, which may cause Infinite loop.

3.for

Format

for(;;){     //第一个分号前面内容只会执行一次并且在进入循坏整体之前,用于初始化变量
             //第二个分号前面用于判断循坏条件,表达式为1继续,为0结束循环
             //第二个分号后面一般用于改变循环条件,会在执行一次循坏后自动执行
             //括号是循坏执行语句的主体
}

detail:

The content in () can be omitted, but the semicolon cannot be omitted. After omitting everything, you must change the loop condition in {} or use break. If part is omitted, complete the omitted part. The first part can be completely omitted, but if there are variables, they must be initialized before that. What can be solved with while can definitely be solved with for, but it doesn't work anyway.

In addition, these loops support nested use, and the do while loop is executed at least once. The for loop is more convenient than while, because the initialization, loop condition judgment and loop condition change are together, which is more intuitive and reduces search.

Guess you like

Origin blog.csdn.net/m0_74316391/article/details/130488305