C language branch and loop statements

What is a statement?

C statements can be divided into the following five categories:

  1. expression statement
  2. function call statement
  3. control statement
  4. compound statement
  5. Empty statement (an empty statement means that I need this statement, but do not want this statement to do anything)
    The control statement will be introduced later.
    Control statements are used to control the execution flow of the program to realize various structural methods of the program. They are composed of specific statement definers. C language
    has Nine types of control statements.
    can be divided into the following three categories:
  6. Conditional judgment statements are also called branch statements: if statements, switch statements;
  7. Loop execution statements: do while statement, while statement, for statement;
  8. Turn statements: break statement, goto statement, continue statement, return statement.

Branch statement (selection structure)

If you don’t study hard, you will go home and farm. If you study hard, you can find a good job. This is your choice.
The choices include one of two, one of three, and one of many.
1.if statement
Grammatical structure of if statement:

//单分支:
if(表达式)
语句;
//双分支:
if(表达式)
语句;
else
语句;
//多分支:
if(表达式)
语句;
else if(表达式)
语句;
else if(表达式) 
语句;
........
else
语句;

Note:
If the statement is true, the statement will be executed; if it is false, the statement will not be executed. In the C language, 0 is false and non-0 is true.

The expression in if brackets refers to an expression with a value, like a function it will return a value.

How should we use code blocks if multiple statements are to be executed if the condition is true.

#include <stdio.h>
int main()
{
    
    
    if(表达式)
   {
    
    
        语句列表1}
    else
   {
    
    
        语句列表2}
    return 0;
    }

The { } here is a code block.
1.1 leave empty else
when you write this code

#include <stdio.h>
int main()
{
    
    
    int a = 0;
    int b = 2;
    if(a == 1)
        if(b == 2)
            printf("hehe\n");
    else
        printf("haha\n");
    return 0;
}

Writing code like this will give a very vague feeling. Which if does the else here correspond to?
We can change it to this:

//适当的使用{}可以使代码的逻辑更加清楚。
//代码风格很重要
#include <stdio.h>
int main()
{
    
    
    int a = 0;
    int b = 2;
    if(a == 1)
   {
    
    
        if(b == 2)
       {
    
    
            printf("hehe\n");
       }
   }
    else
   {
    
    
         printf("haha\n");
   }       
    return 0;
}

In this way, we can see at a glance which if else corresponds to, so the style of the code is very important. A good coding style can make your logic clearer.
Note:
else is equipped with the if that is closest to it.
2. switch statement
The switch statement is also a branch statement, but it is more suitable for multiple branches.
For example:
Input 1, output Monday
Input 2, output Tuesday
Input 3. Output Wednesday
Input 4 and output Thursday
Input 5 and output Friday
Input 6 and output Saturday
Input 7, output Sunday
If you use if...else if..., it will be too complicated and cumbersome.
The syntax form of switch statement:

switch(整型表达式)
{
    
    
	语句项;
}

What is a statement item?

case(整型常量表达式):
语句;

The statement items are these case statements
Let’s use the switch statement to implement the above example

#include <stdio.h>
int main()
{
    
    
    int day = 0;
    switch(day)
   {
    
    
        case 1printf("星期一\n");
            break;
        case 2:
            printf("星期二\n");
            break;
        case 3:
            printf("星期三\n");
            break;    
        case 4:
            printf("星期四\n");
            break;    
        case 5:
            printf("星期五\n");
            break;
        case 6:
            printf("星期六\n");
            break;
        case 7:
            printf("星期天\n");    
            break;
   }
    return 0;
}

The break here achieves the effect of jumping out of the branch in the switch statement
If there is no break statement, it will always execute statements one by one in order.

#include <stdio.h>
int main()
{
    
    
    int day = 0;
    switch(day)
   {
    
    
        case 1printf("星期一\n")case 2:
            printf("星期二\n");
        case 3:
            printf("星期三\n");   
        case 4:
            printf("星期四\n"); 
        case 5:
            printf("星期五\n");
        case 6:
            printf("星期六\n");
        case 7:
            printf("星期天\n"); 
   }
    return 0;
}

When I enter a 1, without a break statement, it will print out everything that follows.
When I enter a 1, without a break statement, it prints out everything that follows.
When I add a break statement and only enter 1, I only enter Monday
The case statement item is whatever I enter, such as I enter 1, then go in from case1:.
Good programming practice:
Add a break statement after the last case statement.
(The reason for writing this is to avoid forgetting to add a break statement after the last case statement).
default clause
What if the value of the expression does not match the values ​​of all case tags?
In fact, it doesn’t matter. The structure is that all statements are skipped.
The program will not terminate and no error will be reported, because this situation is not considered an error in C.
But what if you don’t want to ignore the value of an expression that doesn’t match all tags?
You can add a default clause to the statement list and write the following label
default:
in any case The position where the label can appear.
When the value of the switch expression does not match the values ​​of all case labels, the statement following the default clause will be executed.
Therefore, only one default clause can appear in each switch statement.
But it can appear anywhere in the statement list, and the statement flow will execute the default clause just like a case tag.
Good programming habits:
It is a good habit to put a default clause in each switch statement, and you can even add a break at the end.

loop statement

There are three loop statements in C language:
while loop
if loop
do while loop a>
1.while loop
Let’s first look at the syntax structure of the while loop:

//与if语句很相似
while(表达式)
{
    
    
	循环语句;
}

The execution flow of the while loop: The While loop first enters the judgment expression to judge whether it is true, executes the statement, and then adds 1 to the loop variable. If it is false, jump out of the loop, and the judgment condition must be executed at least once.
Let’s give an example:
Print the numbers 1-10

#include <stdio.h>
int main()
{
    
    
	int i=0;//定义一个初始变量
	while(i<=10)//这是判断条件
	{
    
    
		printf("%d",i);
		i++;//调整部分
	}
	return 0;
}

Let’s take a look at the role of the break statement in the while loop:
Let’s write a code first

#include <stdio.h>
int main()
{
    
    
	int i=0;//定义一个初始变量
	while(i<=10)//这是判断条件
	{
    
    
		if(i==5)
		break;
		printf("%d",i);
		i++;//调整部分
	}
	return 0;
}

Only 1, 2, 3, 4 are printed
The break statement can be derived from the running results to jump out of the loop directly.
We can also verify our results through debugging.
Through these verification methods, we conclude that the role of the break statement in the while statement is to permanently terminate the loop. , as long as the break loop is encountered, the loop will terminate.
Next, let’s explore the impact of continue on the while loop

int main()
{
    
    
	int i = 1;
	while (i <= 10)
	{
    
    
		if (i == 5)
			continue;
		printf("%d ", i);
		i++;
	}
	return 0;
}

After printing 1, 2, 3, and 4, it will loop endlessly l Judging from the running results, after printing 1, 2, 3, 4, there is an infinite loop, which means that the statements after the continue statement are not executed, causing the adjustment part to be unable to be adjusted, and an infinite loop appears a> Let’s first look at the syntax structure of for loop 2. for loop Terminate the loop permanently. As long as the break loop is encountered, the loop will terminate The role of break in the while loop: Skip the code after this loop and go directly to the judgment part to see whether to make the next judgment The role of continue in the while loop: To summarize:
After analysis, I concluded that the effect of the continue statement on the while loop is to skip the code after this loop and go directly to the judgment part to see whether to make the next judgment.






int main()
{
    
    
	for(表达式1;表达式2;表达式3)
	{
    
    
		循环语句;
	}
	return 0;
}

The execution process of the for loop: first execute the initialization part (will only be executed once), then execute the judgment part, then execute the loop statement, and finally execute the adjustment part
We still print 1-10 on screen as example

int main()
{
    
    
	int i = 0;
	for (i=1;i<=10;i++)
	{
    
    
		printf("%d ", i);
	}
	return 0;
}

We compare some for loops and while loops, and we can clearly see that the for loop is simpler and more efficient than the while loop
Let’s continue to explore the impact of the break statement on the for loop

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

Running result:Printed 1, 2, 3, 4
It can be seen from the running result that the break statement directly terminates the loop in the same way as the for loop and the while loop.
The role of Break in the for loop:
Permanently terminates the loop. As long as a break loop is encountered, the loop will terminate.
We Let’s explore the role of the continue statement in the for loop

int main()
{
    
    
	int i = 0;
	for (i=1;i<=10;i++)
	{
    
    
		if (i == 5)
			continue;
		printf("%d ", i);
	}
	return 0;
}

Running result:All are printed except 5
Based on the running result, it is inferred that when i is equal to 5, the following statements are skipped and the adjustment part is reached.
Conclusion: I will skip the statement after continue and go directly to the adjustment part
Suggestion:

  1. Do not modify loop variables within the for loop body to prevent the for loop from losing control.
  2. It is recommended that the loop control variable of the for loop adopts the writing method of "front closed and then open interval"
    Note:
    The initialization, judgment part and adjustment part are all It can be omitted, but if the judgment part is omitted, it means that the judgment part is always true, and it will enter an infinite loop
    3. do while loop
    The syntax of do while loop :
int main()
{
    
    
	do
	{
    
    
		//循环语句;
	} while (表达式);
	return 0;
}

The execution flow of the do while loop:
First execute the loop statement, then enter the adjustment part, and finally enter the judgment statement. The loop body must be executed at least once. The loop body includes loop statements and adjustment parts
We still use the above example to write a piece of code

int main()
{
    
    
	int i = 1;
	do
	{
    
    
		printf("%d ", i);
		i++;
	} while (i<=10);
	return 0;
}

The role of break in do while loop

int main()
{
    
    
	int i = 1;
	do
	{
    
    
		if (i == 5)
			break;
		printf("%d ", i);
		i++;
	} while (i<=10);
	return 0;
}

Running result:Only 1, 2, 3, 4 are printed
According to the running result, it can be seen that the breal statement in the do while loop has the same effect as the first two loops
break in do The role of the while loop:
Permanently terminates the loop. As long as the break loop is encountered, the loop will terminate

The role of continue in do while loop

int main()
{
    
    
	int i = 1;
	do
	{
    
    
		if (i == 5)
			continue;
		printf("%d ", i);
		i++;
	} while (i<=10);
	return 0;
}

Running result:Print 1, 2, 3, 4 and then loop endlessly
From the running result, we can see that the continue statement has the same effect in the do while loop and the while loop.
The role of continue in the do while loop:
Skip the code after this loop and go directly to the judgment part to see if the next judgment is made

goto phrase

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.
However, the goto statement is still useful in some situations. The most common usage is to terminate the processing of certain deeply nested structures.
.
For example: jump out of two or more levels of loops at a time.
In the case of multi-level loops, using break will not achieve the purpose. It can only exit from the innermost loop to the loop of the previous level.
Let me give you an example of a scenario using goto statement
A shutdown program

#include<stdlib.h>
int main()
{
    
    
	char input[20] = {
    
     0 };
	system("shutdown -s -t 60");
	again:
	printf("本机器在1分钟之后关机,如果输入GGband就取消关机\n");
	scanf("%s", &input);
	if (strcmp(input, "GGband") == 0)
	{
    
    
		system("shutdown -a");
	}
	else
	{
    
    
		goto again;
	}

	return 0;

Goto statement: can only jump within the same function, not across functions.
End of this chapter...

Guess you like

Origin blog.csdn.net/HD_13/article/details/132225845