C language loop structure (loop statement)

Table of contents

1. Use the while statement to realize the loop

 Second, the do...while statement realizes the loop

Comparison of while loop and do...while loop

Third, use the for statement to realize the loop

4. Change the state of loop execution

1. Use the break statement to terminate the loop early

2. Use the continue statement to end this loop early

3. The difference between break statement and continue statement


Preface: In the previous content, we introduced the selection structure, but only these two structures are not enough in our program, we need to use the loop structure that will be learned today. In our daily life or in the problems dealt with by programs, we often encounter problems that need to be dealt with repeatedly. For example:

  • To input the grades of 50 students in the class to the computer (repeat the same input operation 50 times)
  • Find the average grades of 50 students respectively (repeat the same calculation operation 50 times)
  • Check whether the grades of 30 students are qualified (repeat the same judgment operation 30 times)

To deal with the above problems, the most primitive method is to write several identical or similar statements or program segments for processing. For example: Statistics of 50 students' grades in 5 courses

//输入一个同学的5门成绩
scanf("%f %f %f %f %f",&score1,&score2,&score3,&score4,&score5);

Then repeat writing 49 same programs. Although the requirements can be fulfilled in this way, this approach is not advisable, because the workload is heavy, the program is lengthy, and it is difficult to read and maintain. We can use the loop structure provided by the computer to solve the operations that need to be repeated.

int i=0;
while(i<=50)
{
    scanf("%f %f %f %f %f",&score1,&score2,&score3,&score4,&score5);
    i++;
}

We can see that a while statement solves the problem of repeating the program 50 times.

Note: sequence structure, selection structure and loop structure are the three basic structures of structured programming, and they are the basic building blocks of various complex programs. Proficiency in the concept and use of selection structures and loop structures is the most basic requirement for programming.

1. Use the while statement to realize the loop

//while语句的一般形式

while(表达式)

        语句

The "statement" is the body of the loop. The loop body can only be one statement, which can be a simple statement or a compound statement (several statements enclosed in curly braces). The number of times the loop body is executed is controlled by the loop condition, which is an "expression" in general form, and it is also called a loop condition expression . When the value of the expression is "true" (indicated by a non-zero value), the statement of the loop body is executed; when the value of the expression is "false" (indicated by 0), the structure of the loop body is not executed.

The while statement can be simply recorded as: as long as the loop condition expression is true (that is, the given condition is established), the loop body statement is executed.

Note: The characteristic of the while loop is to judge the conditional expression first, and then execute the loop body statement.

As shown in the figure: the execution process of this program is: variable i=1 at the beginning, and the while statement first judges whether the variable i is less than or equal to 50. If it is true, the statement (loop body) behind the while statement is executed. The function of "i++" at the end of the loop body is to increase the value of i by 1, and now the value of i is 2, and then the process returns to the beginning of while and executes again until the value of i is greater than 50 to end the loop.                                                              

 Second, the do...while statement realizes the loop

//do……while语句的一般形式
do
    语句
while(表达式)

Note: The characteristic of the do...while statement is that it executes the loop body unconditionally first, and then judges whether the loop condition is true.

Comparison of while loop and do...while loop

1. while loop

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

Running results (twice)

 

 

2. do... while loop

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

 Execution result (twice)

 

 It can be seen that when the value of input i is less than or equal to 10, the results of the two are the same; and when the value of i is greater than 10, the results of the two are different, because i>10 (the value of the expression is false ) At this time, for the while loop, the loop body is not executed once, but for the do...while loop, the loop body is executed at least once.

Third, use the for statement to realize the loop

//for语句的一般形式
for(表达式1;表达式2;表达式3)
//  初始化    判断     调整
    语句

The role of the 3 expressions:

Expression 1: The initialization of the variable in the loop body is executed only once, and can be zero, one or more. Example: i=1

Expression 2: loop body conditional expression, used to judge whether to execute the loop. Execute this expression first in each loop execution, and continue to execute the loop when the decision is made.

Expression 3: The adjustment of the loop body variable is performed after the loop body is executed.

illustrate:

1. Expression 1 can be omitted, that is, the initial value is not set, but the semicolon after expression 1 cannot be omitted. For example:

for(;i<100;i++)

Note: Since the expression 1 is omitted, no value is assigned to the initial variable, so the loop variable must be assigned a value before the for statement.

2. The expression 2 is omitted, that is, the expression 2 is not used as the loop condition expression, and the loop condition is not set and checked, that is, the expression 2 is always true, the loop will continue endlessly, and the program loops endlessly. For example:

for(i=1;;i++)

4. Change the state of loop execution

1. Use the break statement to terminate the loop early

As mentioned above, using the break statement can make the process jump out of the switch structure and continue to execute the next statement in the switch statement. break can also be used in a loop structure to jump out of the loop body, that is, to jump out of the loop in advance.

#include <stdio.h>
int main()
{
	int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		if (5 == arr[i])
		{
			break;
		}
		printf("%d ", arr[i]);
	}
}

 

Note: The break statement can only be used in loop statements and switch statements, and cannot be used alone.

2. Use the continue statement to end this loop early

Sometimes you don't want to end the operation of the entire loop, you just want to end this loop ahead of time, and then execute the next loop. At this time, you can use the continue statement

#include <stdio.h>
int main()
{
	int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		if (5 == arr[i])
		{
			continue;
		}
		printf("%d ", arr[i]);
	}
}

 Program analysis: When arr[i] is equal to 5, execute the continue statement, the process skips the printf function statement, ends this loop, and then adjusts the loop variable. As long as i<10, the next loop will be executed.

3. The difference between break statement and continue statement

The continue statement only ends the current loop, rather than terminating the execution of the entire loop. The break statement ends the entire loop process, and does not judge whether the condition for executing the loop is true.

(1)
while(表达式1)
{
    语句1;
    if(表达式2)
        break;
    语句2;
}
(2)
while(表达式1)
{
    语句1;
    if(表达式2)
        continue;
    语句2;
}

The flowchart of program (1) is shown in Figure 5.13, and the flow of program (2) is shown in Figure 5.14

 If there is a double loop, there is a break statement in the inner loop, which will terminate the inner loop early. (The process jumps outside the inner loop)

I hope this blog is helpful and rewarding to everyone. I hope you can give me a free like. Thank you for your support.

If you have any questions or comments, you can leave a message in the comment area.

Guess you like

Origin blog.csdn.net/2301_76207836/article/details/130204288