Elementary C language - branch and loop statement (on)

"Flowers will bloom along the way, and so will the road in the future." Today, let's take a closer look at branch statements and loop statements.

1. What is a statement?

In C language, 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
    3 + 2;//表达式语句
	printf("Hello World!\n");//函数调用语句
	;//空语句-当我们需要一条语句,但这条语句什么都不需要做,那么我们可以选择空语句

Here we focus on the control statement, which is used to control the execution flow of the program to realize various structural modes of the program, and they are composed of specific statement definers. There are 9 control statements in C language:

1. The conditional judgment statement is the branch statement:

  • if
  • switch

2. Loop execution statement

  • while
  • for
  • do…while

3. Turn to statement

  • goto statement
  • break statement
  • continue statement
  • return statement

2. Branch statement (choice structure)

2.1 if statement

语法结构:
if(表达式)//表达式结果为真,语句被执行;表达式结果为假,语句就不会被执行。
     语句;   

Note: In C language: 0 means false, non-zero means true
The following is an example:

#include <stdio.h>
int main()
{
    
    
	int age = 0;
	scanf("%d",&age);
	if (age >= 18)
		printf("成年人!\n");
	return 0;
}

insert image description here

Double branch if statement:

if(表达式)//表达式为真,语句1被执行;表达式为假,语句2被执行
     语句1else
     语句2

Examples are given below:

#include <stdio.h>
int main()
{
    
    
	int age = 0;
	scanf("%d",&age);
	if (age >= 18)
		printf("成年人!\n");
	else
		printf("未成年人!\n");
	return 0;
}

insert image description here
insert image description here

Multi-branch if statement:

if(表达式1)
     语句1else if(表达式2)
     语句2;
else
     语句3

Examples are given below:

#include <stdio.h>
int main()
{
    
    
	int age = 0;
	scanf("%d",&age);
	if (age < 18)
		printf("未成年人!\n");
	else if (age >= 18 && age <= 40)//这行的表达式不能写成18<=age<=40!!!
		printf("青年!\n");
	else if (age > 40 && age <= 65)
		printf("中年!\n");
	else
		printf("老年!\n");
	return 0;
}

insert image description here
insert image description here
Here is a piece of code: let’s think about what is the execution result of this code?

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

Here, at a glance, everyone's first thought may be to print hihi on the screen, but in fact, nothing should be printed, and it can be run here for everyone to see.
insert image description here
Why is this so?Here we need to pay attention, under normal circumstances, else matches the nearest if==, after the above code specification, it should be as follows:

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

From the above code, we know that the expression a==1 in the first if statement is not true, so the nested if statement below will directly jump out, and the printout will not be executed.

2.1.1 if statement practice

1. Determine whether a number is odd or not?

#include <stdio.h>
int main()
{
    
    
	int n;
	scanf("%d", &n);
	if (n % 2 == 1)
		printf("Yes!\n");
	else
		printf("No!\n");
	return 0;
}

insert image description here
insert image description here
2. Output all odd numbers from 1 to 100

//输出1~100的奇数
//方法一:
#include <stdio.h>
int main()
{
    
    
	int n = 1;
	while (n <= 100)
	{
    
    
		if (n % 2 == 1)
			printf("%d ", n);
		n++;
	}
	return 0;
}
//方法二:
#include <stdio.h>
int main()
{
    
    
	int n = 1;
	while (n <= 100)
	{
    
    
	    printf("%d ", n);
		n = n + 2;y		
	}
	return 0;
}

insert image description here

2.2 switch statement

The switch statement is also a branch statement, often used in multi-branch situations.

For example:
input 1, output Monday
input 2, output Tuesday
input 3, output Wednesday
input 4, output Thursday
input 5, output Friday
input 6, output Saturday
input 7, output Saturday

There is a multi-branch situation here, and it is more complicated to express it with an if statement. To use a different grammatical form, here we can consider the switch statement.

switch(整形表达式)//表达式的结果必须是整型,根据表达式的值来选择相应的语句项来执行
{
    
    
    语句项://语句项是一些case语句
    //示例如下:
    case 整型常量表达式:
         语句;
}

For the above example, we give the following piece of code:

#include <stdio.h>
int main()
{
    
    
	int day = 0;
	scanf("%d", &day);
	switch (day)
	{
    
    
	case 1:
		printf("星期一!\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;
}

So, is this right? Let's run it for a try:
insert image description here
We can find that when we input 3, it not only prints Wednesday, but also executes the following statement items, and the execution process is as follows: However, we don't want it to print so
insert image description here
many out, but only want to print a Wednesday, so how should we adjust it?
Here we introduce the break in the switch statement

2.2.1 break in switch statement

In the switch statement, we can't directly realize the branch, and we can realize the real branch by using it with break.
Then let's modify the above code and change it to what we want:

#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");
		break;
	case 4:
		printf("星期四!\n");
		break;
	case 5:
		printf("星期五!\n");
		break;
	case 6:
		printf("星期六!\n");
		break;
	case 7:
		printf("星期天!\n");
		break;
	}
	return 0;
}

insert image description here
Next, we give this example a change, you can try to write: when inputting 1-5, output weekday, when outputting 6-7, output weekend. Here is my code:

#include <stdio.h>
int main()
{
    
    
	int day;
	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;
}

insert image description here
insert image description here
At this time, there is also a problem, that is, when I enter 8, can I give a prompt? Here we introduce the default clause.

2.2.2 default clause

What if the value of the expression does not match the value of any case label? That is, all statements are skipped, the program will not be terminated, and no error will be reported. In C, it does not consider this an error. But what if you don't want to ignore the value of the expression that doesn't match all tags? You can add a default clause to the list, and the default clause can appear anywhere a case label can appear. When the value of the switch expression does not match the value 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 as if it were a case label. Here we can modify the above code:

#include <stdio.h>
int main()
{
    
    
	int day;
	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("选择错误!\n");
		break;
	}
	return 0;
}

insert image description here

3. Loop statement

  • while
  • for
  • do while

3.1 while loop

Earlier, we had the if statement:

if(条件)
     语句;

We know that when the condition is met, the if statement is executed, otherwise it is not executed. But this statement will only be executed once. But in daily life, we find that the same thing may require us to do it many times. So, what should we do? Here we introduce the while statement:

while(表达式)
    循环语句;

The execution flow of the while statement is: first judge the value of the expression, and if the value of the expression is true, execute the loop statement. Then the expression is judged, as long as it is true, the loop body is executed, and so on, until the value of the expression is 0, and the loop is jumped out.
Let's give an example below: If we want to print the numbers from 1 to 10 on the screen, how should we do it?

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

insert image description here
The basic syntax of while has been learned above, and then we will learn more about it:

3.1.1 break and continue in while statement

What is the output of the following code?

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

You can run it for a try, we can find that there is an infinite loop, and the cursor keeps flashing behind 4.
insert image description here
Why is this? There is no problem with n from 1 to 4, but when n=5, it encounters continue and jumps out of the current cycle, and the following statement is not executed. At this time, n is still 5, and it encounters continue again, jumping out of this cycle The code after the second loop repeats this way, and the value of n will always be 5, entering an infinite loop.

The role of continue in the while loop: continue is used to terminate this loop, that is, the code behind continue in this loop will not be executed again, but will jump to the judgment part of the while statement to enter the next loop judge.

Still the above example, when we put n++ on the if statement, what will happen?

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

It is not difficult to see that the n here first performs the +1 operation and prints out, and only jumps out when n=5, so it will print out 2~4, 6~11.
insert image description here
So, we already know about continue, so what is the role of break?

//break语句:
#include <stdio.h>
int main()
{
    
    
	int n = 1;
	while (n <= 10)
	{
    
    
		if (n == 5)
			break;
		printf("%d ", n);
		n++;
	}
	return 0;
}

insert image description here
Here, why only 1~4 are output? Here, we give the usage of break!

The function 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. All, the break in while is to terminate the loop forever.

3.2 getchar() and putchar() statements

getchar()-Get (input) a character, when the character is successfully read, return the ASCII code value of the character, and return EOF (-1) when the read fails or encounter the end of the file) putchar()-Output a
character

#include <stdio.h>
int main()
{
    
    
	int ch = getchar();
	putchar(ch);
	return 0;
}

insert image description here
We found that the above code can accept and print out that character!
Next, let's take a look at the following code and see what it is used for?

#include <stdio.h>
int main()
{
    
    
	int ch = 0;
	while ((ch = getchar())!= EOF)
	{
    
    
		if (ch < '0' || ch>'9')
			continue;
		putchar(ch);
	}
	return 0;
}

For the research of this code, we need to figure out the ASCII code value. We have actually shown it to you before, and here we show it to you: we
insert image description here
can find that the above code means only printing the character 0 The characters between ~9, through the ASCII code table, we found that the corresponding number characters are 0 ~9. What this code does is print only numeric characters, skipping other characters. Through the sample output below, we can also find this result. When running, we found that the cursor will keep blinking down, and the program cannot exit. At this time, we can press ctrl+Z+Enter on the keyboard to solve this problem.
insert image description here

Alright, that’s all for today. Welcome to follow, like and comment!

Guess you like

Origin blog.csdn.net/qq_73121173/article/details/131787816