C++ stage 01 notes 04 [program flow structure (selection structure, loop structure, jump statement)]

C++| Ingenious work from 0 to 1 introductory programming [video + courseware + notes + source code]

table of Contents

4 Program flow structure

4.1 Choosing a structure

4.1.1 if statement

——①Single-line format if statement

——②Multi-line format if statement

——③Multi-condition if statement

——④Nested if statement

4.1.2 Ternary Operator

4.1.3 switch statement

4.2 Loop structure

4.2.1 while loop statement

——While loop exercise case: guess the number

4.2.2 do...while loop statement

——Do...while loop exercise case: the number of daffodils

4.2.3 for loop statement

——For loop exercise case: knock on the table

4.2.4 Nested loops

——For loop nesting practice case: multiplication formula table

4.3 Jump statement

4.3.1 break statement

——Example

4.3.2 continue statement

——Example

4.3.3 goto statement

——Example


4 Program flow structure

C/C++ supports the most basic three program running structures: sequence structure, selection structure, and loop structure .

  • Sequence structure: The program is executed in sequence without jumps.

  • Selection structure: According to whether the conditions are met, the corresponding functions are selectively executed.

  • Loop structure: According to whether the condition is met, a certain piece of code is executed repeatedly in a loop.

4.1 Choosing a structure

4.1.1 if statement

Role: Execute the statement that meets the conditions.

Three forms of if statement

  1. Single-line format if statement

  2. Multi-line format if statement

  3. Multi-condition if statement

——①Single-line format if statement

Single-line format if statement:if(条件){ 条件满足执行的语句 }

Example:

#include <iostream>
using namespace std;

int main()
{
	//选择结构-单行if语句
	//用户输入一个分数,如果分数大于600分,视为考上一本大学,并在屏幕上打印(输出)

	//1、用户输入分数
	int score = 0;
	cout << "请输入一个分数:" << endl;
	cin >> score;

	//2、打印用户输入的分数
	cout << "您输入的分数为: " << score << endl;

	//3、判断分数是否大于600,如果大于600,则输出...
	//if语句
	//注意事项,在if判断语句后面,不要加分号
	if (score > 600)
	{
		cout << "我考上了一本大学!!!" << endl;
	}

	return 0;
}

Note: Do not add a semicolon after the if conditional expression.

——②Multi-line format if statement

Multi-line format if statement:if(条件){ 条件满足执行的语句 }else{ 条件不满足执行的语句 };

Example:

#include <iostream>
using namespace std;

int main()
{
	//选择结构-多行if语句
	//输入考试分数,如果分数大于600,视为考上一本大学,在屏幕上输出
	//如果没考上一本大学,打印"未考上一本大学"

	//1、输入考试分数
	int score = 0;
	cout << "请输入考试分数:" << endl;
	cin >> score;

	//2、提示用户输入的分数
	cout << "您输入的分数为:" << score << endl;

	//3、判断如果大于600,打印“考上一本”,否则打印"未考上一本"
	if (score > 600) //大于600分执行下面大括号中的内容
	{
		cout << "我考上了一本大学!" << endl;
	}
	else//不大于600分,执行else后大括号中的内容
	{
		cout << "我未考上一本大学!" << endl;
	}

	system("pause");

	return 0;
}

——③Multi-condition if statement

Multi-condition if statement:if(条件1){ 条件1满足执行的语句 }else if(条件2){条件2满足执行的语句}... else{ 都不满足执行的语句}

Example:

 

#include <iostream>
using namespace std;

int main()
{
	//选择结构-多行if语句
	int score = 0;

	cout << "请输入考试分数:" << endl;

	cin >> score;

	if (score > 600)
	{
		cout << "我考上了一本大学!" << endl;
	}
	else if (score > 500)
	{
		cout << "我考上了二本大学!" << endl;
	}
	else if (score > 400)
	{
		cout << "我考上了三本大学!" << endl;
	}
	else
	{
		cout << "我未考上本科!" << endl;
	}

	system("pause");

	return 0;
}

——④Nested if statement

Nested if statement : In if statement, you can nest if statement to achieve more precise condition judgment.

Case requirements:

  • Prompt the user to enter a score for the college entrance examination, and make the following judgments based on the score

  • If the score is greater than 600 points, it is considered to be admitted to one book, if the score is greater than 500, it is considered to be admitted to two books, if the score is greater than 400, it is considered to be admitted to three books, and the rest are regarded as not being admitted to the undergraduate course;

  • In a score, if the score is greater than 700, it is admitted to Peking University, if it is greater than 650, it is admitted to Tsinghua University, and if it is greater than 600, it is admitted to the National People's University.

Example:

 

#include <iostream>
using namespace std;

int main()
{
    int score = 0;
    cout << "请输入考试分数:" << endl;
    cin >> score;

    if (score > 600)
    {
        cout << "我考上了一本大学!" << endl;
        if (score > 700)
        {
            cout << "我考上了北大!" << endl;
        }
        else if (score > 650)
        {
            cout << "我考上了清华!" << endl;
        }
        else
        {
            cout << "我考上了人大!" << endl;
        }
    }
    else if (score > 500)
    {
        cout << "我考上了二本大学!" << endl;
    }
    else if (score > 400)
    {
        cout << "我考上了三本大学!" << endl;
    }
    else
    {
        cout << "我未考上本科!" << endl;
    }

    system("pause");
    return 0;
}

Practice case: weighing three little pigs

There are three piglets ABC. Please input the weight of the three piglets separately and determine which piglet is the heaviest?

 

#include <iostream>
using namespace std;

int main()
{
    //三个小猪称体重,判断哪只小猪最重

    //1、创建三只小猪的体重变量
    int A = 0;
    int B = 0;
    int C = 0;

    //2、让用户输入三只小猪的体重
    cout << "\n请输入小猪A的体重:" << endl;
    cin >> A;

    cout << "\n请输入小猪B的体重:" << endl;
    cin >> B;

    cout << "\n请输入小猪C的体重:" << endl;
    cin >> C;

    cout << "\n小猪A的体重为:" << A << endl;
    cout << "小猪B的体重为:" << B << endl;
    cout << "小猪C的体重为:" << C << endl;

    //3、判断三只哪只小猪最重
    //先判断A和B重量
    if (A > B) //A比B重
    {
        if (A > C)
        {
            cout << "\n小猪A最重!\n" << endl;
        }
        else
        {
            cout << "\n小猪C最重!\n" << endl;
        }
    }
    else //B比A重
    {
        if (B > C)
        {
            cout << "\n小猪B最重!\n" << endl;
        }
        else
        {
            cout << "\n小猪C最重!\n" << endl;
        }
    }

    system("pause");

    return 0;
}

4.1.2 Ternary Operator

Function: Simple judgment is achieved through the ternary operator.

grammar:表达式1 ? 表达式2 :表达式3

Explanation:

If the value of expression 1 is true, execute expression 2 and return the result of expression 2;

If the value of expression 1 is false, expression 3 is executed, and the result of expression 3 is returned.

Example:

#include <iostream>
using namespace std;

int main()
{
	//三目运算符
	int a = 10;
	int b = 20;
	int c = 0;

	c = a > b ? a : b;
	cout << "c = " << c << endl; //c = 20
	c = (a > b ? a : b);
	cout << "c = " << c << endl; //c = 20

	//C++中三目运算符返回的是变量,可以继续赋值

	(a > b ? a : b) = 100;

	cout << "a = " << a << endl; //a = 10
	cout << "b = " << b << endl; //b = 100
	cout << "c = " << c << endl; //c = 20

	system("pause");

	return 0;
}

Summary: Compared with the if statement, the ternary operator has the advantage of being short and neat, but the disadvantage is that if it is nested, the structure is not clear.

4.1.3 switch statement

Role: Execute multiple conditional branch statements.

grammar:

switch (expression) //[ expression type in switch statement can only be integer or character ]

{

    case result 1: execute statement; break;

    case result 2: execute statement; break;

    ...

    default: execute statement; break;

}

Example:

#include <iostream>
using namespace std;

int main() //switch语句
{
	//请给电影进行评分
	// 10 ~ 9   经典
	// 8 ~ 7   非常好
	// 6 ~ 5   一般
	// 5分以下 烂片

	//1、提示用户给电影评分
	cout << "请给电影打分:" << endl;

	//2、用户开始进行打分
	int score = 0;
	cin >> score;
	cout << "您打的分数为:" << score << endl;

	//3、根据用户输入的分数来提示用户最后的结果
	switch (score)
	{
	case 10:
		// cout << "您认为是经典电影!" << endl;
		// break; //退出当前分支
	case 9:
		cout << "您认为是经典电影!" << endl;
		break; //退出当前分支
	case 8:
		// cout << "您认为电影非常好!" << endl;
		// break;
	case 7:
		cout << "您认为电影非常好!" << endl;
		break;
	case 6:
	case 5:
		cout << "您认为电影一般!" << endl;
		break;
	default:
		cout << "您认为是烂片!" << endl;
		break;
	}

	//if和switch区别?
	//switch缺点:判断时候只能是整型或者字符型,不可以是一个区间!
	//switch优点:结构清晰,执行效率高!

	system("pause");

	return 0;
}

Note 1: The expression type in the switch statement can only be integer or character type .

Note 2: If there is no break in the case, the program will be executed all the way down.

Summary: Compared with the if statement, for multi-condition judgment, the structure of switch is clear and the execution efficiency is high. The disadvantage is that the switch cannot judge the interval.

4.2 Loop structure

4.2.1 while loop statement

Role: to meet the loop conditions, execute loop statements

grammar:while(循环条件){ 循环语句 }

Explanation: As long as the result of the loop condition is true, the loop statement is executed.

Example:

#include <iostream>
using namespace std;

int main()
{
	//while循环
	//在屏幕上打印 0 ~ 9 这10个数字
	int num = 0;
	//while()中填入循环条件
	//注意事项:在写循环时,一定要避免死循环的出现。while (1)死循环
	while (num < 10)
	{ // 循环代码
		cout << "num = " << num << endl;
		num++;
	}
	system("pause");
	return 0;
}

Note: When executing a loop statement, the program must provide an exit to jump out of the loop, otherwise an infinite loop will occur.

——While loop exercise case: guess the number

While loop exercise case: guess the number

Case description: The system randomly generates a number between 1 and 100, and the player makes a guess. If the guess is wrong, it will prompt the player that the number is too large or too small. If the guess is correct, congratulate the player for victory and exit the game.

#include <ctime> // time system time header file

//Add random number seed, function: use the current system time to generate random numbers to prevent random numbers from being the same every time.

srand((unsigned int)time(NULL));

#include <iostream>
#include <ctime> // time系统时间头文件
using namespace std;

int main()
{
	//添加随机数种子,作用:利用当前系统时间生成随机数,防止每次随机数都是一样。
	srand((unsigned int)time(NULL));

	//1、系统生成随机数【rand() % 100:生成0~99的随机数】
	int num = rand() % 100 + 1; //rand()%100+1 生成 0+1 ~ 99+1 的随机数
	cout << "系统生成随机数(0~99):" << num << endl;

	//2、玩家进行猜数
	int val = 0; //玩家输入数据

	while (1) //死循环
	{
		cin >> val;

		//3、判断玩家的猜测
		//猜错:提示猜的结果 过大或过小,重新返回第二步
		if (val > num)
		{
			cout << "猜测过大!\n"
				 << endl;
		}
		else if (val < num)
		{
			cout << "猜测过小!\n"
				 << endl;
		}
		else
		{
			cout << "猜测正确!\n"
				 << endl;
			//猜对:退出游戏
			break; //break, 可以利用该关键字退出当前循环。
		}
	}

	system("pause");

	return 0;
}

4.2.2 do...while loop statement

Role: to meet the loop conditions, execute loop statements.

grammar: do{ 循环语句 } while(循环条件);

Note: The difference with while is that do...while will execute the loop statement once , and then judge the loop condition.

Example:

#include <iostream>
using namespace std;

int main()
{
	//do...while循环语句
	//在屏幕中输出0~9这10个数字
	int num = 0;
	do
	{
		cout << num << endl;
		num++;
	} while (num < 10);

	num = 0;
	do
	{
		cout << num << endl;
		num++;
	} while (num); // 死循环!!!

	num = 0;
	//while (num < 10 ) // 输出0~9
	while (num) //不执行任何代码
	{
		cout << num << endl;
		num++;
	}

	//do...while和while循环区别在于do...while会先执行一次循环语句

	system("pause");

	return 0;
}

Summary: The difference from the while loop is that do...while executes the loop statement once, and then judges the loop condition.

——Do...while loop exercise case: the number of daffodils

Practice case: Number of daffodils

Case description: The number of daffodils refers to a 3-digit number, and the sum of the digits to the power of 3 is equal to itself.

For example: 1^3 + 5^3+ 3^3 = 153

Please use the do...while statement to find the number of daffodils in all three digits.

#include <iostream>
using namespace std;

int main()
{
	//1、先打印所有的三位数
	int num = 100;

	do
	{
		//2、从所有的三位数字中找到水仙花数
		int a = 0; //个位
		int b = 0; //十位
		int c = 0; //百位

		a = num % 10;	   //获取数字的个位
		b = num / 10 % 10; //获取数字的十位
		c = num / 100;	   //获取数字的百位

		if (a * a * a + b * b * b + c * c * c == num) //如果是水仙花数,才打印
		{
			cout << num << endl;
		}
		num++;

	} while (num < 1000);

	system("pause");

	return 0;
}

4.2.3 for loop statement

Role: to meet the loop conditions, execute loop statements.

grammar:for(起始表达式;条件表达式;末尾循环体) { 循环语句; }

Example:

#include <iostream>
using namespace std;

int main()
{
	//for循环
	//打印数字0~9
	for (int i = 0; i < 10; i++)
	{
		cout << i << endl;
	}

	//同义拆分
	int i = 0;
	for (;;)
	{
		if (i >= 10)
		{
			break;
		}
		cout << i << endl;
		i++;
	}

	system("pause");

	return 0;
}

Detailed explanation:

Note: The expressions in the for loop must be separated by semicolons.

Summary: while, do...while, for are all commonly used loop statements in development, and the for loop structure is clearer and more commonly used.

——For loop exercise case: knock on the table

Practice case: knock on the table

Case description: Counting from 1 to the number 100. If the ones place of the number contains 7, or the ten place of the number contains 7, or the number is a multiple of 7, we print out the table and print out the rest of the numbers directly.

 

#include <iostream>
using namespace std;

int main()
{
	//1、先输出1~100数字
	for (int i = 1; i <= 100; i++)
	{
		//2、从100个数中找到特殊的数字,打印“敲桌子!”
		//如果是7的倍数、个位是7、十位是7,打印“敲桌子!”
		if (i % 7 == 0 || i % 10 == 7 || i / 10 == 7) //如果是特殊数字,打印“敲桌子!”
		{
			cout << "敲桌子!" << endl;
		}
		else //如果不是特殊数字,打印数字
		{
			cout << i << endl;
		}
	}

	system("pause");

	return 0;
}

4.2.4 Nested loops

Function: Nest a layer of loops in the loop body to solve some practical problems.

For example, if we want to print the following picture on the screen, we need to use nested loops.

 

#include <iostream>
using namespace std;

int main()
{
	//利用嵌套循环实现星图
	//外层循环执行1次,内层循环执行1轮(1周)
	for (int i = 0; i < 10; i++) //外层循环:打印一行星图
	{
		for (int j = 0; j < 10; j++) //内层循环:打印一行*
		{
			cout << "*"
				 << " "; //*加空格
		}
		cout << endl; //换行
	}
	return 0;
}

——For loop nesting practice case: multiplication formula table

Practice case: Multiplication formula table

Case description: Use nested loops to realize multiplication table of nine to nine.

#include <iostream>
using namespace std;

int main()
{
	//乘法口诀表
	for (int i = 1; i <= 9; i++) //打印行数
	{
		// cout << i << endl;
		for (int j = 1; j <= i; j++) //打印列数
		{
			cout << j << "*" << i << "=" << i * j << "  ";
		}
		cout << endl;
	}
	system("pause");
	return 0;
}

4.3 Jump statement

4.3.1 break statement

Function: Used to jump out of the selection structure or the loop structure .

When to break:

  • Appears in the switch conditional statement, the role is to terminate the case and jump out of the switch.

  • Appears in the loop statement, the role is to jump out of the current loop statement.

  • Appears in a nested loop, jumping out of the nearest inner loop statement.

——Example

#include <iostream>
using namespace std;

int main() //break的使用时机
{
	//1、在switch语句中使用break
	cout << "请选择您挑战副本的难度:" << endl;
	cout << "1、普通!" << endl;
	cout << "2、中等!" << endl;
	cout << "3、困难!" << endl;
	int num = 0; //创建选择结果的变量
	cin >> num;	 //等待用户输入
	switch (num)
	{
	case 1:
		cout << "您选择的是普通难度!" << endl;
		break; //退出switch语句
	case 2:
		cout << "您选择的是中等难度!" << endl;
		break;
	case 3:
		cout << "您选择的是困难难度!" << endl;
		break;
	}

	//2、在循环语句中用break
	for (int i = 0; i < 10; i++)
	{
		if (i == 5) //如果i等于5,退出循环,不再打印
		{
			break; // 跳出循环语句
		}
		cout << i << endl;
	}

	//3、在嵌套循环语句中使用break,退出内层循环【出现在嵌套循环语句中】
	for (int i = 0; i < 10; i++)
	{
		for (int j = 0; j < 10; j++)
		{
			if (j == 5)
			{
				break; //退出内层循环
			}
			cout << "*" << " ";
		}
		cout << endl;
	}

	return 0;
}

4.3.2 continue statement

Function: In the loop statement , skip the remaining unexecuted statements in this loop, and continue to execute the next loop.

——Example

#include <iostream>
using namespace std;

int main()
{
	//continue语句
	for (int i = 0; i < 100; i++)
	{
		if (i % 2 == 0) //奇数输出,偶数不输出,0 2 4 6 8 10
		{
			continue; //作用:可以筛选条件,执行到此就不再向下执行;执行下一次循环
					  //break会退出循环,而continue不会
		}
		cout << i << endl;
	}
	system("pause");
	return 0;
}

Note: continue does not terminate the entire loop, and break will jump out of the loop.

4.3.3 goto statement

Function: You can jump to the statement unconditionally.

Grammar: goto 标记;  such as: goto FLAG; [Generally use pure capital words!

Explanation: If the marked name exists, when the goto statement is executed, it will jump to the marked position.

——Example

  

#include <iostream>
using namespace std;

int main() //goto语句
{
	cout << "1、xxx" << endl;
	cout << "2、xxx" << endl;

	goto FLAG;

	cout << "3、xxx" << endl;
	cout << "4、xxx" << endl;

FLAG:

	cout << "5、xxx" << endl;

	system("pause");

	return 0;
}

Note: It is not recommended to use the goto statement in the program, so as not to cause confusion in the program flow.

Guess you like

Origin blog.csdn.net/weixin_44949135/article/details/115135458