Take you to see the whole picture of branch and loop statement - this one is enough

foreword

In the C language, statements can be divided into five categories: expression statements, function call statements, control statements, compound statements, and empty statements . This article will introduce the control statement in detail.
Control statements are used to control the execution flow of the program to realize various structural modes of the program ( sequence structure, loop structure, selection structure ), and they are composed of specific statement definers. There are 9 control statements
in C language , which can be divided into the following three categories:

  1. Conditional judgment statements are also called branch statements: if statement, switch statement
  2. Loop execution statement: do while statement, while statement, for statement
  3. Turn statement: break statement, goto statement, continue statement, return statement

1. Branch statement (choice structure)

Study hard in university, get a good offer from school recruits, reach the pinnacle of life, marry Bai Fumei; do not study hard, sell sweet potatoes at home after graduation; or other.
This is choice.
insert image description here

1.1 if statement

In C language, the if statement can realize both single branch and multi-branch . What about the grammatical structure?

//语法结构
//单分支
if(表达式)
     语句;
//多分支
if(表达式)
	语句1;
else
	语句2;
//更多分支
if(表达式1)
	语句1;
else if(表达式)
	语句2;
else
	语句3;

Tips:

  • In C, a statement executes if the expression evaluates to true . The C language stipulates that 0 means false and non-zero means true .
  • If the above expression is true, to execute multiple statements, put the code block in { } .
  • When a dangling else appears, the else matches the if closest to it, not the else to which it matches .
  • When judging constant expressions (such as judging whether 5 and sum are equal), readers are advised to write 5==sum (this can prevent readers from writing one less = in the process of actually writing code, and write the judgment statement as an assignment statement)

1.2 switch statement

The switch statement is also a branch statement, often used in multi-branch situations .
For example, if the following situation occurs:
input 4-7, the corresponding output is Thursday to Saturday.
If we write it in the form of if...else if...else if..., it is undoubtedly too complicated. The C language gives a good solution - the switch statement .

//switch语句
switch(整形表达式)
{
    
    
	语句项;		//语句项是一些case语句
}				//如下:
				//case 整型表达式:
				//		语句;

1.2.1 break in switch statement

In the switch statement, we can't directly realize the branch, and the real branch can only be realized after matching the break .
For example: we require to input 4 and 5, output weekday; input 6 and 7, output weekend
Our code can be implemented like this:

#include <stdio.h>
int main()
{
    
    
	int day = 0;
	scanf("%d", &day);
	switch (day)
	{
    
    
	case 4:
	case 5:
		printf("weekday\n");
		break;
	case 6:
	case 7:
		printf("weekend\n");
		break;
	}
	return 0;
}
  • The actual effect of break is to divide the list of statements into different branching parts .
  • switch () can only be a constant expression .
  • Good programming habit : add a break statement after the last case statement . (Writing this way can avoid forgetting to add a break statement after the previous last case statement when you or others want to modify the code in the future)

1.2.2 default statement

In the actual process, what if the value of the expression does not match the value of any case label?
In fact, it's nothing, the structure is to skip all the statements. But what's interesting is that the program does not stop or report an error (in this case, C does not consider it an error).
If we don't want to ignore all tags that don't match, we can add a default statement to the list of statements.

  • When the value of the switch expression does not match the values ​​of all case labels, the statement after default will be executed.

  • Only one default statement can appear in each switch statement

  • The default statement can appear anywhere in the statement list, and the default statement will be executed like a case label when executed

  • Good programming habit : add a default statement to each switch statement, and you can even add a break statement after it.

2. Loop statement

  • while
  • for
  • do while

Let's look at a simple loop
insert image description here

2.1 while loop

There are many situations in life: the same thing needs to be done multiple times, but the if statement can only be executed once, so what should I do?
The C language introduces the while statement , which can implement loops .

while syntax structure:

while (表达式)
	循环语句;

The execution flow chart of the while statement:

insert image description here
Instance: How to print the numbers 1-10 on the screen.
We can achieve this like this:

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

2.1.1 break in while statement

break introduction

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

What is the output of these codes?

insert image description here
Summary:
The role of break in the while loop:
In fact, as long as a break is encountered in the loop, all subsequent loops will be stopped and the loop will be terminated directly, so the break in while is used to permanently terminate the loop .

2.1.2 continue in while statement

continueIntroduction

//continue  代码实例
#include <stdio.h>
int main()
{
    
    
	int i = 0;
	while (i < 10)
	{
    
    
		i = i + 1;
		if (i == 5)
			continue;
		printf("%d ", i);
	}
	return 0;
}

This code just changes break to continue. What is the output of the code?

insert image description here

After running the code, we found that except for 5, other numbers are output normally.
Summary:
The function of continue in while is:

continue is used to terminate this cycle, that is, the code after continue in this cycle will not be executed again, but will directly jump to the judgment part of while to judge the entry of the next cycle.

2.2 for loop

First, let's look at the syntax of the for loop:

2.2.1 Syntax

for(表达式1:表达式2:表达式3
	循环语句;		
//表达式1为初始化部分,用于初始化循环变量的。
//表达式2为条件判断部分,用于判断循环什么时候终止
//表达式3为调整部分,用于循环部分的调整

The execution flow chart of the for loop:
insert image description here

Tips:

  • Comparing the for loop and the while loop, we can find that there are still three necessary conditions in the while loop, but due to style problems, the three parts of the while loop may deviate far away, resulting in insufficient concentration and convenience for searching and modifying . Therefore, the style of the for loop is even better, and the frequency of use is also higher .

  • In a for loop, break and continue have the same meaning as a while loop.

  • Suggestion 1: Do not modify the loop variable in the body of the for loop to prevent the for loop from getting out of control.

  • Suggestion 2: The value of the control variable of the for loop adopts the writing method of " before closing and then opening interval ".

2.2.2 Some for loop variants

Let's look at the following 4 pieces of code to see what the result is and how many hehes are printed.

#include <stdio.h>
int main()
{
    
    
	//代码1
	for (;;)
	{
    
    
		printf("hehe\n");
	}
	//代码1运行,会死循环打印hehe

	//代码2
	int i = 0;
	int j = 0;
	for (; i < 10; i++) 
	{
    
    
		for (; j < i; j++)
		{
    
    
			printf("hehe\n");	//j初始化省略,j在第一次循环结束后会,不会从0开始,而是保持原来的值
		}
	}
	//代码2运行,打印10个hehe

	//代码3——使用多哥变量控制循环
	int x, y;
	for (x = 0, y = 0; x < 2 && y < 5; x++, y++)
	{
    
    
		printf("hehe\n");
	}
	//代码3运行,打印2个hehe
	return 0;
}
  1. In the for loop, the omission of the initialization and adjustment parts is to do nothing.
  2. In the for loop, the omission of the judgment part means that the judgment is always true.

2.3 do...while() loop

2.3.1 Syntax of the do statement

do
	循环语句;
while(表达式);

2.3.2 Execution process

insert image description here

2.3.3 Features of the do statement

When the do statement loops, it is executed at least once, but the scene is limited, so it is not often used.

#include <stdio.h>
int main ()
{
    
    
	int i = 1;
	do
	{
    
    
		printf("%d ", i);	//不管如何,先执行代码块中内容,在判断是否在执行
		i++;
	} while (i <= 10);
	return 0;
}

- The meaning of break and continue in the do while statement is the same as that of the while statement and the for statement.

3. goto statement

The C language provides goto statements and labels that mark jumps that can be abused at will. Theoretically, the goto statement is not necessary. In practice, the code can be easily written without the goto statement. But in some occasions, the goto statement can still be used. The most common usage is to terminate the program during the processing of some deeply nested structures.
For example: Jump out of two or more layers of loops at a time. (Using break in this case of a multi-layer loop is useless, it can only exit from the inner loop to the previous loop)

The scenarios where the goto statement is really suitable are as follows:

for (...)
{
    
    
	for (...)
	{
    
     ...
		for (...)
		{
    
    
			if (disaster)
				goto error;
		}
	}
}
error:
	if(disaster)
		//处理错误情况

end

This is the end of this article, hoping to help readers better understand the overall picture of the control structure and establish a complete logical framework. It is not easy to create, if you think this article is helpful to you, remember to like and pay attention. thank you for your support!
C simple program detailed explanation, take you to quickly start C language

Guess you like

Origin blog.csdn.net/Zhenyu_Coder/article/details/130283326