C Language Practice Chapter 2--Branches and Loops

Table of contents

foreword

2.1 Branch statement

2.1.1 What is a statement

2.2 Branch statement

2.2.1 Grammatical form of if statement

2.2.2 Dangling else problem

2.2.3 Comparison of writing forms of if

2.3 switch statement

2.3.1 The grammatical form of switch

2.3.2 The relationship between switch and break

2.3.3 The relationship between switch and default


foreword

Friends, the Dragon Boat Festival is safe and healthy! Today we start a new chapter of learning! Start learning directly!

2.1 Branch statement

2.1.1 What is a statement

Before understanding the statement, let's understand the following knowledge first! C language is a structured programming language! So what is structured or what are structured? Structuring mainly includes: sequence structure, loop structure, selection structure!

 The selection structure corresponds to the branch statement (if switch statement), and the loop structure corresponds to the loop statement (while, for, do while). Closer to home, what is a sentence? Statements are separated by semicolons . There are five types of statements in C language:

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

Check out the code for details!

#include<stdio.h>
int main()
{
	3 + 5;//表达式语句
	printf("haha\n");//函数调用语句
	;//空语句
	return 0;
}

Today we are going to talk about control statements! Control statements are used to control the execution flow of the program to realize various structural modes of the program (c language supports three structures: sequence structure, selection structure, and loop structure). They are composed of specific semantic symbols. C language consists of nine control statements that can be Divided into the following three categories:

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

2.2 Branch statement

2.2.1 Grammatical form of if statement

//if的单分支语法结构
if (表达式)
   语句式;

//If的双分支的语法结构
if (表达式)
  语句式;
else
   语句式;

//if的多分支语法结构
if (表达式)
语句式;
else if (表达式)
语句式;
else if (表达式)
语句式;
else;

Taking age as an example, let's take a look at the specific use of if! When the age is less than 18, we need to print minors, first use the if single branch to try it out

 Oh well, when we input 13, it really prints underage, so what if we print out adults when we input more than 18, what should we do if we can fall in love? Then add the code

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

Run it to see if it meets our expectations

 It looks like it came here according to our expectations! Let's enter another value to see, what will happen when we enter 13?

 At this time, it was even printed that you can fall in love! But 13 is not an adult! At this time, we will find that there is an error in the code but the program did not make an error when compiling! So how should we change it? An error will be reported here because one statement is controlled by default after If, and curly braces are used when there are multiple statements!

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

At this time, we can enter 13 again and there will be no problem (at the same time, the above is also the way of writing compound sentences)

 To sum up: the If statement controls one statement by default, and curly braces are used when there are multiple statements!

Let's use the code to see the double branch of If

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

This statement is also very simple, but there is one point that needs attention: you cannot directly follow the statement after else!

#include<stdio.h>
int main()
{
	int age = 0;
	scanf("%d", &age);
	if (age < 18)
	{
		printf("未成年\n");
	}
	else(age >= 20)//代码在编译期间会报错
	{
		printf("青年人\n");
	}
	return 0;
}

If you want to follow the statement after else, you have to add an if. At this time, you need to use multiple branches. The above code

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

There are two things to note about the above code:

  1. Else cannot be directly followed by a statement, but else if can be directly followed by a statement (emphasis again)! !
  2.  Mathematical writing is not allowed: 50<=age<=100 is wrong, this writing is correct age>=50&&age<=100

2.2.2 Dangling else problem

Go directly to the code!

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

Will it print hehe or haha1 or both or neither? Let's ctrl+f5 to see the result together!

 At this time, we will find that nothing is printed, why is this! This is because the else only matches the closest if and not the closest! So our code should look like this

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

For better understanding, you can also use { } after if

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

From this code we draw two points:

  1. Else matches the nearest if
  2. Pay attention to the code style when writing code.

Regarding the code style, I recommend you to read "High Quality C/C++ Programming" written by Dr. Lin Rui , which has a good description!

2.2.3 Comparison of writing forms of if

//第一种                              
if (condition) {
	return x;
}
return y;
//第二种
if (condition)
{
	return x;
}
else
{
	return y;
}

Comparing these two, which one do you think is easy and clear to read? That's right, the second type! Once again, I must read "High Quality C/C++ Programming" written by Dr. Lin Rui!

2.3 switch statement

2.3.1 The grammatical form of switch

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

The statement items are composed of case statements! So what is the structure of the case statement, the code!

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

Among them, it is worth noting that: the integer expression in the switch determines the entry of the case!

2.3.2 The relationship between switch and break

Topic: Enter 1 to 7 to get the corresponding week, take the topic as an example to familiarize yourself with the syntax of switch

#include<stdio.h>
int main()
{
	int day = 0;
	scanf("%d", &day);
	switch (day)
	{
	case 1:
		printf("星期1\n");
	case 2:
		printf("星期2\n");
	case 3:
		printf("星期3\n");
	case 4:
		printf("星期4\n");
	case 5:
		printf("星期5\n");
	case 6:
		printf("星期6\n");
	case 7:
		printf("星期天\n");
	}
	return 0;
}

Well written, let’s run it again to see the result

 We entered 2 and the week 2 we wanted did appear, but why did it also appear from week 3 to Sunday? This has to introduce the relationship between switch and break. In the switch, the case determines the entry, and the break determines the exit. If there is no break in the statement, it will continue to execute.

#include<stdio.h>
int main()
{
	int day = 0;
	scanf("%d", &day);
	switch (day)
	{
	case 1:
		printf("星期1\n");
        break;
	case 2:
		printf("星期2\n");
        break;
	case 3:
		printf("星期3\n");
        break;
	case 4:
		printf("星期4\n");
        break;
	case 5:
		printf("星期5\n");
        break;
	case 6:
		printf("星期6\n");
        break;
	case 7:
		printf("星期天\n");
        break;
	}
	return 0;
}

 Now we can get the result we want! Then if we want to output weekday from 1 to Friday, and weekend on Saturday and Sunday! Or write it as before? no no no we should make some changes

#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");
	}
	return 0;
}

Isn't this much simpler! To summarize again:

  • With break in switch, real branch can be realized
  • The actual effect of the break statement is to divide the statement list into different branch parts

Finally, one more note: add a break statement after the last case statement, this is to avoid forgetting to add a break statement in the previous case statement.

2.3.3 The relationship between switch and default

When the input value does not match all the items, the code does not report an error when it runs, but we can use the default statement when we don't want it. The position of the default statement can be written anywhere in the case statement. The default statement should also be followed by a break , use the code to see the specific implementation form.

#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");
	default:
		printf("输入错误\n");
		break;
	}
	return 0;
}

 Briefly summarize

  • When the value of the switch expression does not match the value of any case label, the statement after the default clause will be executed
  • There is a space between case and integer constant expression

That's all for today's content, Dragon Boat Festival Ankang Sauce! !

Guess you like

Origin blog.csdn.net/2301_77886098/article/details/131340872