C Language Learning - Chapter 5 Loop Structure Programming ②

Get into the habit of writing together! This is the 11th day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the details of the event .

nesting of loops

A loop body contains another complete loop structure, which is called the nesting of loops . 3 kinds of loops (while loop, do...while loop and for loop) can be nested in each other, such as:

(1) while
while() {
    ...
    while() { // 内层循环
        ...
    }
}
2do...while
do {
    ...
    do { // 内层循环
        ...
    } while()
} while()
3for
for(;;) {
    for(;;) { // 内层循环
        ...
    }
}

(4) while, do...while
while(){
    ...
    do{ // 内层循环
        ...
    } while()
}
5for, while // ※
for(;;) {
    ...
    while () { // 内层循环
        ...
    }
}

(6) do...while, for
do {
    ...
    for (;;) { // 内层循环
        ...
    }
} while()
复制代码

Comparison of several cycles

  • All 3 kinds of loops can be used to deal with the same problem, in general, they can replace each other
  • In while and do...while loops, the loop condition is only specified in the parentheses after while, so in order for the loop to end normally, the statement that makes the loop tend to end should be included in the loop body (such as i++, i = i + 1 Wait). for loops can contain operations in expression 3 that cause the loop to end
  • With while and do...while loops, the initialization of the loop traversal should be done before the loop statement. The for statement can also complete the initialization of variables in expression 1
  • while, do...while和for循环都可以用break语句跳出循环,用continue语句结束本次循环。

Change the state of the loop execution

  • Terminate a loop early with a break statement

The general form of the break statement :

break;
复制代码

The effect is to make the process jump outside the loop body, and then execute the statement below the loop body

break语句只能用于循环语句和switch语句中,不能单独使用

  • Use the continue statement to end the loop early

The general form is:

continue;
复制代码

Effect: end this cycle early , and then execute the next cycle

  • Difference between break statement and continue statement※
    • The continue statement only ends the current loop, not the execution of the entire loop.
    • The break statement ends the entire loop process, and no longer judges whether the conditions for executing the loop are established

Example of a loop program

  • Input two positive integers m and n, find their greatest common divisor and least common multiple

  • Output all "daffodil numbers", the so-called "daffodils number" refers to a 3-digit number whose cubic sum of the digits is equal to the number itself. For example, 153 is the number of daffodils because 153 = 1³ + 5³ + 3³.

  • Use dichotomy to find the roots of the following equation at (-10, 10): 2x³ - 4x² + 3x - 6 = 0

Guess you like

Origin juejin.im/post/7085026059929780261