C language --- branch and loop statement

1. What is a sentence

C language statements can be divided into five categories:

  • expression statement
  • function call statement
  • control statement
  • compound statement
  • empty statement

C language has nine control statements

Can be divided into three categories:

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

2. if statement

Syntax structure of if statement:

if (表达式)             //表达式结果如果为真或者非0,那这个表达式就会运行
    语句;
if (表达式)           
    语句;             //这里如果只有一条语句,那就不需要带{},也可以带
else
    语句2;


if (表达式)           
    语句1;             //这里大于一条语句,那就需要带{}
	语句2;
else
    语句2;
//多分支
if (表达式1)           
    语句;            
else if(表达式2)
    语句2;
else
    语句3;


//注意:如果一个表达式同时满足if语句有满足else if语句,因为if语句先接收的这个表达式,那这个表达式只会进入到if语句里面。

2.1, if is matched with the nearest else

Let's look at the code first:

#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;
}

output:

insert image description here

Obviously the output here is empty! ! !

What is this asking? Shouldn't it be the result of the output: haha? Why not?

This is because the else will match the nearest if , so the output is empty.

insert image description here

So the structure of the code should be like 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;
}

Summary: else and if are matched by the nearest, not that else and if are matched in the same indentation.

3. switch statement

The switch statement is also a branch statement

Often used in multi-branch situations

for example:

输入1,输出星期一
输入2,输出星期二
输入3,输出星期三
输入4,输出星期四
输入5,输出星期五
输入6,输出星期六

grammar:

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

And what is the statement item?

//语句项是一些case语句
//如下:
case 整形常量表达式      //case后面必须是整形常量,当然使用字母表示也行,因为字母的ASCII也是整数
    语句;

Use switch to realize week query

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main()
{	
	int day = 0;
	scanf("%d", &day);
	switch (day)
	{
	case 1:
		printf("星期一\n");
		break;
	case 2:
		printf("星期二\n");
		break;
	case 3:
		printf("星期三\n");

	case 4:
		printf("星期四\n");
		break;
	case 5:
		printf("星期五\n");
		break;
	case 6:
		printf("星期六\n");
		break;
	case 7:
		printf("星期日\n");
		break;
	}
	return 0;
}

Let's talk about the switch principle:

Enter the corresponding number from the switch, and find the corresponding case statement according to the number, so that it enters the switch statement, and then exits the switch statement through the break statement after matching.

3.1. New requirements

Require:

  • Input 1-5, output "weekday"
  • Input 6-7, output "weekend"
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main()
{	
	int day = 0;
	scanf("%d", &day);
	switch (day)
	{
	case 1:
	case 2:
	case 3:
	case 4:
	case 5:
		printf("weekday\n");
		break;
	case 6:
	case 7:
		printf("weekend\n");
		break;
	}
	return 0;
}

This shows that the case statement is executed downwards before the break statement is encountered, and the switch statement will not be jumped out until the break statement is encountered.

3.2, default sentence

What if the value of the expression does not match the value of any case label?

In fact, it's nothing, if they don't match, they will definitely skip them all in the end.

The program will not terminate, nor will it report an error, but when there is no match, we will finally prompt.

Then this requires the default clause.

Note: Only one default clause can appear in the switch statement

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main()
{	
	int day = 0;
	scanf("%d", &day);
	switch (day)
	{
	case 1:
	case 2:
	case 3:
	case 4:
	case 5:
		printf("weekday\n");
		break;
	case 6:
	case 7:
		printf("weekend\n");
		break;
	default:                         //所示
		printf("输出错误");
		break;
	}
	return 0;
}

output:

insert image description here

4. Loop statement

  • while
  • for
  • do while

4.1、while

Grammatical structures

while (表达式)
{
    循环语句;
}

4.1.1, break statement

As long as the break statement is executed in the while loop, the entire while loop will stop. If the break statement is in any part of the while loop, the while will terminate immediately.

Code example:

#include <stdio.h>
int main()
{
	int a = 1;
	while (a < 11)
	{
		if (5 == a)
		{
			break;      //这个break语句看着是在if语句中。但是一旦它被执行,那么整个while语句将会停止
		}
		printf("%d\n",a);
		a++;
	}
	return 0;
}

output:

insert image description here

4.1.2, continue statement

Once the continue statement is executed in the while statement, the loop will directly skip the code after continue, and then judge the loop. If it continues, it will directly proceed to the next loop (execute directly from while (a<11)) .

#include <stdio.h>
int main()
{
	int a = 1;
	while (a < 11)
	{
		if (5 == a)
		{
			continue;        //当a=5时,不在执行后面的代码,直接跳过从while循环开始
		}
		printf("%d\n",a);
		a++;
	}
	return 0;
}

Output: output of endless loop: 1 2 3 4

insert image description here

4.2. Use the while loop to clean up the buffer

4.2.1, getchar() and putchar()

  • The getchar() function is used to read data from the keyboard just like scanf
  • The putchar() function is used to output data
#include <stdio.h>
int main()
{
	int ch = getchar();   //我们在键盘中输入“e”,这个e会被转为相应的ASCII值存入ch中
	printf("%c\n", ch);   //然后在转为字符(%c)进行输出
	putchar(ch);          //这个可以直接输出,和上面的打印的效果是一样的,这是另一种方法
	return 0;
}

output:

insert image description here

But here we have a question:

int ch = getchar(); 

Obviously getchar() receives a character, why do we use int type to receive it? Why not receive char type?

Here is an explanation:
because when a character is read, it will be converted to the corresponding ASCII code value, so it is no problem to put it in the int type.

Important: If getchar() encounters an error/abnormality during the reading process or encounters the end of the file, then this function will return an EOF

EOF--------end of file file end mark

Let's take a look at the definition of EOF (define)

#define EOF    (-1)

You can see that the value defined by EOF is -1, and -1 is an integer, so we should accept the data returned by getchar() with int type

Well, knowing these, we can use the while loop to realize the function of cleaning the buffer:

#include <stdio.h>
int main()
{
	int ch = 0;
	while ((ch = getchar()) != EOF)    //这里ch接收getcha返回的数据不等于EOF,说明返回的是个正常的字符,那就可以正常输出
	{
		putchar(ch);
	}
	return 0;
}

output:

insert image description here

You will find that the output will not stop, this is Ctrl+z, and then press Enter to terminate the program.

Ctrl+z is to let getchar return an EOF, so that the program terminates

[Key points:] Let's understand the logic of this program:

Here's a question first? Why does the output above wrap automatically?

缓冲区The concept designed here

As we know scanf, getcharthe function is used to get data from the keyboard, as soon as we output characters from the keyboard, scanfcan getcharthe function receive it? Actually not, the correct sequence is: when we output a character on the keyboard, the character will enter the buffer. At this time scanf, getcharthe function detects that there is a character in the buffer. At this time scanf, getcharthe function will take the character out of the buffer.

Then why is it automatically wrapping?

insert image description here

Still the above code flow analysis: when we enter "a" and press Enter, (Enter is equivalent to entering \n), first judge a!=EOF, so execute putchar(ch) and then print out "a", and then again Loop, because "a" in the buffer has been read, so there is "\n" left, and then getchar reads directly, because "\n"!=EOF, so putchar(ch) is executed next time, so It will automatically wrap.

4.2.2. In-depth analysis - clean up the buffer code

Let's look at the code first:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main()
{
	char password[20] = { 0 };
	printf("请输入密码:>");
	scanf("%s", password);   //这里不用在&password,因为数组名就是数组首元素地址,所以不用取地址
	printf("请确认密码(Y/N):>");
	int ret = getchar();
	if (ret == 'Y')
		printf("Yes\n");
	else
	{
		printf("No\n");
	}
	return 0;
}

output:

insert image description here

Obviously such an output result is wrong, obviously I haven’t confirmed it yet, the program prints NO directly

Analysis: When we enter: abcdef on the keyboard, and then press Enter (\n), there is: "abcdef\n" in the input buffer at this time, and scanf commands to fetch what it needs. So scanf took "abcdef" away, so password = "abcdef", but at this time there is still a "\n" in the buffer, and then the program goes down to getchar to get the data, and there is a "\n" in the buffer \n", so getchar directly takes away "\n", and then enters the if judgment, "\n"!='Y', so the program outputs No.

insert image description here

How to solve it? We can find a way to just let there be no characters in the buffer, which can be achieved like this:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main()
{
	char password[20] = { 0 };
	printf("请输入密码:>");
	scanf("%s", password);   
	getchar();     //这里在添加个getchar(),提前把那个\n读取掉,那下面那个getchar()就可以正确判断了
	printf("请确认密码(Y/N):>");
	int ret = getchar();
	if (ret == 'Y')
		printf("Yes\n");
	else
	{
		printf("No\n");
	}
	return 0;
}

But this way of writing is relatively rude and does not apply to every situation. For example: we enter on the keyboard: abcdef sdf (with a space in the middle)

insert image description here

This is no longer possible. Let's analyze why it went wrong again:

First, scanf will read "abcdef" in the buffer, that is to say, scanf will read before the space, and then the first getchar() will read the space, which is equivalent to the first getchar() being used , and then the following getchar() will read sdf, because 'sdf' != 'y', so it will output No.

This is what we can perceive. The solution to the first error is to clean up one character in the buffer, and this requires cleaning up many characters in the buffer to solve it, so we need to solve it in a loop.

We can use getchar() to read all the spaces to "sdf" and the following "\n" in a loop, and that's it.

Let's implement a correct method:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main()
{
	char password[20] = { 0 };
	printf("请输入密码:>");
	scanf("%s", password);   
	int ch = 0;                          //start
	while ((ch = getchar()) != '\n')
	{
		;
	}                                    //end
	printf("请确认密码(Y/N):>");
	int ret = getchar();
	if (ret == 'Y')
		printf("Yes\n");
	else
	{
		printf("No\n");
	}
	return 0;
}

5. for loop

5.1. Grammar

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

__Expression 1: __Expression 1 is the initialization part, which is used to initialize the loop variable.

__Expression 2: __Expression 2 is the condition judgment part, which is used to judge the termination of the loop.

__Expression 3:__Expression 3 is the adjustment part, which is used to adjust the loop condition.

For loop execution order:

The first loop:

insert image description here

The 2nd, 3rd, 4th, 5th, 6th... cycle:

insert image description here

5.2、break,continue

The break statement has the same effect in a for loop as in a while loop.

There is also a small difference between the continue statement in the for loop and the while loop

As shown below:

insert image description here

Among them, the for loop skips the following code after meeting the continue statement, and then jumps to "i++" (adjustment)

The second while loop jumps to the judgment after encountering the continue statement.

5.3, the loop control variable of the for statement

suggestion:

  • Do not modify the loop variable in the for loop body to prevent the for loop from getting out of control.
  • It is recommended that the value of the loop control variable of the for statement be written in the form of "close before and open after".

5.4. Variations of the for loop

1. Infinite loop

#include <stdio.h>
int main()
{
    
    
	for (;;)
	{
    
    
		printf("hehe\n");
	}
	return 0;
}

__Conclusion: __The omission of the judgment part of the for loop means that the judgment or constant is established, and it is okay to omit the initialization and adjustment (but it is best not to omit it).

2. The for loop uses multiple variables to control

#include <stdio.h>
int main()
{
	int x, y;
	for (x = 0, y = 0; x < 2 && y>5; ++x, y++)
	{
		printf("hehe\n");
	}
	return 0;
}

6. do-while loop

6.1, do syntax

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

Print 1-10:

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

The do loop loops at least once.

6.2、break和continue

Works the same.

7. goto statement

The C language provides goto statements that can be abused at will and labels that mark jumps

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 is still useful. The most common usage is to terminate the processing of the program in some deeply nested structures.

For example: Jump out of two or more layers of loops at a time.

Multi-layer loops use break in this case to achieve the purpose, it can only loop from the inner layer to the upper layer.

First look at the effect of goto:

#include <stdio.h>
int main()
{
again:                     //标签
	printf("hehe\n");
	printf("haha\n");
	goto again;
	return 0;
}


//但是goto不能跨函数跳转,如下就是不行的
void test()
{
	again;
}

int main()
{
	printf("hehe\n");
	printf("haha\n");
	goto again;
	return 0;
}

insert image description here

Scenarios where the goto statement is really suitable:

for (...)
	{
    	for (...)
        {
            for (...)
            {
                if (disaster)
                    goto error;            #这样可以根据error标签直接跳过两层for循环
            }
        }
    error:
    	if (disaster)
            //处理错误情况
	}

7.1. Use goto statement to simulate shutdown program

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <Windows.h>
#include <string.h>
int main()
{
	char input[20] = { 0 };
	system("shutdown -s -t 60");             //电脑在60s内关机
again:
	printf("电脑即将在60秒内关机,如果不想关机,输入:我是猪,即可解决。\n");
	scanf("%s", input);
	if (strcmp(input, "我是猪") == 0)
	{
		system("shutdown -a");
		printf("已取消关机\n");
	}
	else
	{
		goto again;
	}
	return 0;
}

Output effect:

insert image description here

Of course, we can also use a loop instead of goto

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <Windows.h>
#include <string.h>
int main()
{
	char input[20] = { 0 };
	system("shutdown -s -t 60");             //电脑在60s内关机
	while (1)
	{
		printf("电脑即将在60秒内关机,如果不想关机,输入:我是猪,即可解决。\n");
		scanf("%s", input);
		if (strcmp(input, "我是猪") == 0)
		{
			system("shutdown -a");
			printf("已取消关机\n");
			break;
		}
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/m0_57776598/article/details/130947349