Continuing from the previous chapter in the book, C language loop structure:

Loops can be used to execute multiple statements multiple times. The “multiple statements” here are called the loop body. In C language, three types of loops can be used, namely: while, do…while and for.

In these statements, the number of times the loop body is executed repeatedly is controlled by the loop condition, which is called a controlling expression. This is an expression of type scalar, that is, it is an arithmetic expression or a pointer expression. If the value of the control expression is not equal to 0, the loop condition is true; otherwise, the loop condition is false.

The statements break and continue are used to jump out of the loop or return to the head of the loop before it has finished executing.

1.while loop

The syntactic structure of the while statement is very similar to that of the if statement.

1.1 Comparison between if and while

1 if (expression)

2 statements;

3

4

5 while (expression)

6 statements; //If the loop body wants to contain more statements, add braces

Let’s use a code to compare:

//Code 1
#include<stdio.h>

int main()
{
    if(1)
        printf("hehe\\
");//if the following conditions are met, print hehe once
    return 0;
}
//Code 2
#include<stdio.h>

int main()
{
    while(1)
        printf("hehe\\
");//While the following conditions are met, the infinite loop prints hehe
    return 0;
}

This is the difference between the two, while can achieve a loop effect

1.2 Execution flow of while statement

Execution flow chart of while statement

The first step is to execute the judgment expression. If the value of the expression is 0, the loop ends directly; if the value of the expression is not 0, the loop statement is executed. After the statement is executed, the judgment continues to determine whether to proceed to the next time. judge.

1.3 Practical application of while loop

Exercise: Print values from 1 to 10 on the screen

Code:

#include <stdio.h>
int main()
{
    int i = 1;
    while(i<=10)
    {
        printf("%d ", i);
        i = i + 1;
    }
    return 0;
}

1.4 Exercise

Enter a positive integer and print each digit of this integer in reverse order.

For example:

Input?: 1234, Output: 4 3 2 1

Input?: 521, Output: 1 2 5

Question? Analysis

1. To get the lowest bit of n, you can use ?n operation, and the remainder is the lowest bit, for example: 1234 gets 4

2. If you want to remove the lowest bit of n and find the penultimate digit, then use n=n/10 to remove the lowest bit, such as:

n=1234/10 gets 123. Compared with 1234, 123 removes the lowest digit, and 123 gets the last digit 3.

3. Loop through steps 1 and 2, and reach all bits before n becomes 0.

Reference Code:

#include <stdio.h>
int main()
{
    int n = 0;
    scanf("%d", & amp;n);
    while(n)
    {
        printf("%d ", n );
        n /= 10;
    }
    return 0;
}

practise:

Write a program to find the sum of the digits of a natural number n, where the value of n is entered from the keyboard.
[Input form]
Enter only one line and enter the value of n.
[Output form]
The output is only one line, and the corresponding sum value is output.

Analysis: To get the sum of each digit, we can easily think of a decimal number. We can divide it by 10 and take the remainder to get the ones digit of the number. In the same way, if we want to get the tens digit, we divide the number by 10. Then take the remainder after dividing by 10 and so on to get each digit. Add these numbers to get the result.

Code:

#include <stdio.h>
int main()
{
    int n;int sum=0;
    scanf("%d", & amp;n);
    while(n>0)
    {
        sum=sum + n;
        n=n/10;
    }
    printf("sum=%d",sum);
    return 0;
}

2.for loop

2.1 Syntax form of for loop

In the normal process of writing code, the for loop is the most used of the three loops. The syntax i form is as follows:

1 for(expression1;expression2;expression3)

2 statements; //If the loop body wants to contain more statements, add braces

Expression 1 ? Initialization of loop variables

Expression 2 ? Judgment of loop end condition

Expression 3 ?Adjustment of loop variables

2.2 Execution process of for loop

?Execute expression 1 first to initialize the loop variable, and then execute the judgment part of expression 2. If the result of expression 2 == 0, the loop ends; if the result of expression 2 !=0, the loop will be executed. statement, after the loop statement is executed, execute expression 3, adjust the loop variable, and then execute expression 2 to determine whether the result of expression 2 is 0, which determines whether the loop continues.

During the entire loop process, the initialization part of expression 1 is only executed once, and the rest is expression 2, loop statement, and expression 3 in the loop.

2.3 Practice of for loop

Exercise: Print values from 1 to 10 on the screen

Reference Code:

#include <stdio.h>
int main()
{
    int i = 0;
    for(i=1; i<=10; i + + )
    {
        printf("%d ", i);
    }
    return 0;
}

operation result:

2.4 Comparison between while loop and for loop

Both for and while have three parts: initialization, judgment, and adjustment in the process of implementing the loop. However, the three parts of the for loop are often concentrated, which facilitates the maintenance of the code. If there is a lot of code, the three parts of the while loop It’s more scattered, so the for loop is better in form.

2.5 Exercise

Exercise 1:

Calculate the sum of numbers that are multiples of 3 between 1 and 100

#include <stdio.h>
int main()
{
    int i = 0;
    int sum = 0;
    for(i=1; i<=100; i + + )
    {
        if(i % 3 == 0)
            sum + = i;
    }
    printf("%d\\
", sum);
    return 0;
}
//This code can also be optimized
//If we can directly produce numbers that are multiples of ?3, we will save redundant loops and judgments.
#include <stdio.h>
int main()
{
    int i = 0;
    int sum = 0;
    for(i=3; i<=100; i + =3)
    {
        sum + = i;
    }
    printf("%d\\
", sum);
    return 0;
}

3.do–while loop

3.1 Grammar Form

The do while statement is the least used among loop statements. The syntax is as follows:

1 do

2 statements;

3 while(expression);

Both while and for loops are judged first. If the condition is satisfied, it enters the loop and executes the loop statement. If it is not satisfied, it jumps out of the loop; the do while loop directly enters the loop body first and executes the loop statement. , and then execute the judgment expression after while. If the expression is true, it will be executed the next time. If the expression is false, the loop will not continue.

3.2 Execution flow of do while loop

In the do while loop, first execute the “statement” on the diagram. After executing the statement, execute the “judgment expression”. If the result of the judgment expression is !=0, then continue the loop and execute the loop statement; judge The result of the expression == 0, the loop ends. Therefore, in the do while statement, the loop body is executed less than once, which is a special feature of the do while loop.

3.3 Examples of do while loop

Print values from 1 to 10 on the screen

#include <stdio.h>
int main()
{
    int i = 1;
    do
    {
        printf("%d ", i);
        i = i + 1;
    }while(i<=10);
    return 0;
}

3.4 Exercise

Input a positive integer, calculate the number of digits this integer has? For example:

Input?: 1234 Output: 4

Input?: 12 Output: 2

#include <stdio.h>
int main()
{
    int n = 0;
    scanf("%d", & amp;n);
    int cnt = 0;
    do
    {
        cnt + + ;
        n = n / 10;
    } while (n);
        printf("%d\\
", cnt);
    return 0;
}

This does not necessarily require the use of the do while statement, but this code is more suitable for the use of the do while loop, because even if n is 0, it is still a 1-digit number, and the number of digits needs to be counted.

4.break and continue statements

In the process of loop execution, if certain conditions occur, the loop needs to be terminated in advance. This is a common phenomenon. C language provides two keywords, break and continue, which should be used in loops.

The function of break is to form a permanent terminal loop. As long as break is executed, it will jump out of the loop and continue execution.

The function of continue is to skip the code after continue in this loop, which is different in for loop and while loop.

4.1 break and continue in while loop

4.1.1 break example

#include <stdio.h>
int main()
{
    int i = 1;
    while(i<=10)
    {
        if(i==5)
            break;//When i equals 5, execute break and the loop ends.
        printf("%d ", i);
        i = i + 1;
    }
    return 0;
}

operation result:

After printing 1, 2, 3, and 4, when i equals 5, the loop terminates at the break point, no longer printing, and no longer looping. So the function of break is to permanently terminate the loop. As long as break is executed, the loop at the level outside break will terminate. Then when we are in the loop and want to terminate the loop under certain conditions, we can use break to achieve the desired effect.

4.1.2 Example of continue

continue means to continue. What it does in a loop is to skip the code after continue in this loop and continue with the judgment of the next loop. In the code above, what will be the result if break is replaced by continue?

#include <stdio.h>
int main()
{
    int i = 1;
    while(i<=10)
    {
        if(i==5)
            continue;
            //When i equals 5, execute continue, directly skip the continue code, and go to the loop judgment place?
            //Because this skips i = i + 1, so i is always 5, and the program traps and infinite loop
        printf("%d ", i);
        i = i + 1;
    }
    return 0;
}

At this point, we can analyze that continue can help us skip the code after the continue of a certain loop, go directly to the judgment part of the loop, and make the judgment of the next loop. If the adjustment of the loop is after the continue, May cause an infinite loop.

4.2 break and continue in for loop

4.2.1 break example

In fact, like the break in the while loop, the break in the for loop also ends the loop. No matter how many times the loop needs to loop, as long as break is executed, the loop will completely terminate. Let’s go to the code.

#include <stdio.h>
int main()
{
    int i = 1;
    for(i=1; i<=10; i + + )
    {
        if(i==5)
            break;
        printf("%d ", i);
    }
    return 0;
}

The function of break is to permanently terminate the loop. In the future, when a certain condition occurs and we no longer want to continue the loop, we can use break to complete it.

4.2.2 Example of continue

In the code above, what will be the result if break is replaced by continue?

#include <stdio.h>
int main()
{
    int i = 1;
    for(i=1; i<=10; i + + )
    {
        if(i==5)
            continue;//This?continue skips the subsequent printing and comes to the adjustment part of i++
        printf("%d ", i);
    }
    return 0;
}

Therefore, the function of continue in the for loop is to skip the code after continue in this loop and go directly to the adjustment part of the loop. In the future, when a certain condition occurs and certain subsequent operations need to be performed in this loop, continue can be used to achieve this.

Compare the difference between continue in while loop and for loop:

4.3 break and continue in do while loop

The operation of break and continue in the do.while statement is almost the same as that in the while loop. You can test it and experience it.

5. Nesting of loops

We have learned three types of loops before: while, do while, and for. These three types of loops are often nested together to solve the problem better. This is what we call: nested loops. Here we will look at an example. ?.

5.1 Exercise

Find the prime numbers between 100 and 200 and print them on the screen.

Note: A prime number is called a prime number, a number that can only be divisible by 1 and the original number.

Analysis:

1. To find a prime number between 100 and 200, you must first have a number between 100 and 200. This can be solved using a loop.

2. Suppose you want to determine whether i is a prime number. You need to use numbers between 2 and i-1 to divide i. You need to generate numbers between 2 and i-1. You can also use a loop to solve this problem.

3. If there is a number between 2 and i-1 that can divide i, then i is not a prime number. If it cannot be divided evenly, then i is a prime number.

Reference Code:

#include <stdio.h>
int main()
{
    int i = 0;
    //Cycle production? Numbers from 100 to 200
    for(i=100; i<=200; i + + )
    {
        //Determine whether i is a prime number
        //Loop to produce a number between 2~i-1
        int j = 0;
        int flag = 1;//Assume i is a prime number
        for(j=2; j<i; j + + )
        {
            if(i % j == 0)
            {
                flag = 0;
                break;
            }
        }
        if(flag==1)
            printf("%d ", i);
    }
    return 0;
}

6. goto statement

The C language provides a very special syntax, which is the goto statement and jump label. The goto statement can jump to the set label within the same function.

#include <stdio.h>
int main()
{
    printf("hehe\\
");
    goto next:
    printf("haha\\
");
next:
    printf("Skip the printing of haha\\
");
    return 0;
}

If the goto statement is used improperly, it will cause random jumps within the function and disrupt the execution flow of the program. Therefore, our suggestion is to try not to use it; but the goto statement is not the right place. , in multi-layer loop code, if you want to quickly jump out of the use of goto, it is very convenient.

e.g.:

for(...)
{
    for(...)
    {
        for(...)
        {
            if(disaster)
                goto error;
        }
    }
}

error:
    //...

Originally, if the for loop wants to exit early, it must use break. Each break can only jump out of the for loop. If there are three levels of nested loops, three breaks must be used to jump out of the loop, so in this case we use the goto statement. It will be faster.

If you want to know what happens next, listen to the explanation next time! This article is a little rushed. There will be exercises like this in the future that will specifically analyze how to apply loop statements.

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. C Skill Tree Home Page Overview 194899 people are learning the system