4 program flow structure

4 program flow structure

C/C + + supports three basic program running structures: sequential structure, selection structure and loop structure

  • Sequence structure: the program is executed in sequence without jump
  • Select structure: perform corresponding functions selectively according to whether the conditions are met
  • Loop structure: executes a piece of code multiple times according to whether the conditions are met

4.1 selection of structure

4.1.1 if statement

**Function: * * execute qualified statements

Three forms of if statements

  • Single line format if statement
  • Multiline if statement
  • Multi conditional if statement
  1. Single line format if statement: if (condition) {statement executed when the condition is met}
    Example:

    int main() {
    
    	//Select structure - single line if statement
    	//Enter a score. If the score is greater than 600, it will be regarded as entering a university and printed on the screen
    
    	int score = 0;
    	cout << "Please enter a score:" << endl;
    	cin >> score;
    
    	cout << "The score you entered is: " << score << endl;
    
    	//if statement
    	//Note: do not add a semicolon after the if judgment statement
    	if (score > 600)
    	{
    		cout << "I was admitted to a university!!!" << endl;
    	}
    
    	system("pause");
    
    	return 0;
    }
    

Note: do not add a semicolon after the if conditional expression

  1. Multi line format if statement: if (condition) {statement executed when the condition meets} else {statement executed when the condition does not meet};

Example:

int main() {

	int score = 0;

	cout << "Please enter the test score:" << endl;

	cin >> score;

	if (score > 600)
	{
		cout << "I was admitted to a university" << endl;
	}
	else
	{
		cout << "I failed to enter a university" << endl;
	}

	system("pause");

	return 0;
}
  1. Multi conditional if statement: if (condition 1) {condition 1 satisfies the executed statement} else if (condition 2) {condition 2 satisfies the executed statement}... Else {neither satisfies the executed statement}

Example:

	int main() {

	int score = 0;

	cout << "Please enter the test score:" << endl;

	cin >> score;

	if (score > 600)
	{
		cout << "I was admitted to a university" << endl;
	}
	else if (score > 500)
	{
		cout << "I was admitted to two universities" << endl;
	}
	else if (score > 400)
	{
		cout << "I was admitted to three universities" << endl;
	}
	else
	{
		cout << "I didn't go to college" << endl;
	}

	system("pause");

	return 0;
}

Nested if statements: if statements can be nested in if statements to achieve more accurate condition judgment

Case requirements:

  • Prompt the user to enter a college entrance examination score, and make the following judgment according to the score
  • If the score is greater than 600, it will be regarded as one, two and three, and the rest will be regarded as not having been admitted to undergraduate;
  • In a book, if the score is more than 700, you will be admitted to Peking University, more than 650, Tsinghua University and more than 600 to the National People's Congress.

Example:

int main() {

	int score = 0;

	cout << "Please enter the test score:" << endl;

	cin >> score;

	if (score > 600)
	{
		cout << "I was admitted to a university" << endl;
		if (score > 700)
		{
			cout << "I was admitted to Peking University" << endl;
		}
		else if (score > 650)
		{
			cout << "I was admitted to Tsinghua University" << endl;
		}
		else
		{
			cout << "I was admitted to the National People's Congress" << endl;
		}
	
	}
	else if (score > 500)
	{
		cout << "I was admitted to two universities" << endl;
	}
	else if (score > 400)
	{
		cout << "I was admitted to three universities" << endl;
	}
	else
	{
		cout << "I didn't go to college" << endl;
	}

	system("pause");

	return 0;
}

Exercise case: weigh three piglets

There are three piglets ABC. Please input the weight of the three piglets respectively and judge which piglet is the heaviest? [the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-QhWQp41I-1638452706982)(assets / three pigs. jpg)]

4.1.2 ternary operator

Function: realize simple judgment through ternary operator

Syntax: expression 1? Expression 2: expression 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, execute expression 3 and return the result of expression 3.

Example:

int main() {

	int a = 10;
	int b = 20;
	int c = 0;

	c = a > b ? a : b;
	cout << "c = " << c << endl;

	//The ternary operator in C + + returns variables and can continue to assign values

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

	cout << "a = " << a << endl;
	cout << "b = " << b << endl;
	cout << "c = " << c << endl;

	system("pause");

	return 0;
}

Summary: compared with the if statement, the advantage of the ternary operator is short and neat, but the disadvantage is that if nested, the structure is not clear

4.1.3 switch statement

**Function: * * execute multi conditional branch statements

Syntax:

switch(expression)

{

	case Result 1: execute the statement;break;

	case Result 2: execute the statement;break;

	...

	default:Execute statement;break;

}

Example:

int main() {

	//Please rate the movie 
	//10 ~ 9 classic   
	// 8 ~ 7 very good
	// 6 ~ 5 general
	// Rotten film with less than 5 points

	int score = 0;
	cout << "Please rate the movie" << endl;
	cin >> score;

	switch (score)
	{
	case 10:
	case 9:
		cout << "classic" << endl;
		break;
	case 8:
		cout << "very nice" << endl;
		break;
	case 7:
	case 6:
		cout << "commonly" << endl;
		break;
	default:
		cout << "Rotten film" << endl;
		break;
	}

	system("pause");

	return 0;
}

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

Note 2: if there is no break in the case, the program will always execute downward

Conclusion: compared with if statements, for multi condition judgment, switch has clear structure and high execution efficiency. The disadvantage is that switch cannot judge the interval

4.2 circulation structure

4.2.1 while loop statement

**Function: * * execute loop statements when loop conditions are met

Syntax: while (loop condition) {loop statement}

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

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-hSPtIcN5-1638452706983)(assets/clip_image002-1541668640382-20211108124630-ykcs5bd.png)]

Example:

int main() {

	int num = 0;
	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 endless loop will occur

while loop exercise case: guess numbers

**Case description: * * the system randomly generates a number between 1 and 100, and the player guesses. If the guess is wrong, the player will be prompted that the number is too large or too small. If the guess is right, congratulations on the player's victory and exit the game.

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-6JhdZ35f-1638452706984)(assets / guess number. jpg)]

4.2.2 do... while loop statement

Function: execute loop statements when loop conditions are met

Syntax: do {loop statement} while (loop condition);

**Note: * * the difference between * * and while is that do... While will execute a loop statement first, and then judge the loop conditions

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-ZPLxSBcM-1638452706985)(assets/clip_image002-1541671163478-20211108124715-zbl7w00.png)]

Example:

int main() {

	int num = 0;

	do
	{
		cout << num << endl;
		num++;

	} while (num < 10);


	system("pause");

	return 0;
}

Summary: the difference between do... While and while loop is that do... While executes the loop statement once before judging the loop conditions

Exercise case: daffodils

**Case description: * * daffodil number refers to a three digit number, and the sum of the three powers of the numbers in each digit 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 3 digits

4.2.3 for loop statement

Function: execute loop statements when loop conditions are met

Syntax: for (start expression; conditional expression; end loop body) {loop statement;}

Example:

int main() {

	for (int i = 0; i < 10; i++)
	{
		cout << i << endl;
	}

	system("pause");

	return 0;
}

Detailed explanation:

Note: the expressions in the for loop should be separated by semicolons

Summary: while, do... While and for are loop statements commonly used in development. The for loop structure is relatively clear and commonly used

Exercise case: knocking on the table

Case description: count from 1 to 100. If the digit contains 7, or the digit ten contains 7, or the digit is a multiple of 7, we print and knock on the table, and the other digits are printed directly.

4.2.4 nested loops

Function: nest another layer of loop in the loop body to solve some practical problems

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

Example:

int main() {

	//The outer loop is executed once and the inner loop is executed once
	for (int i = 0; i < 10; i++)
	{
		for (int j = 0; j < 10; j++)
		{
			cout << "*" << " ";
		}
		cout << endl;
	}

	system("pause");

	return 0;
}

**Exercise case: * * multiplication formula table

Case description: use nested loop to realize 99 multiplication table

4.3 jump statement

4.3.1 break statement

Function: used to jump out of the selection structure or loop structure

When to use break:

  • It appears in the switch conditional statement to terminate the case and jump out of the switch
  • Appears in a loop statement to jump out of the current loop statement
  • Appears in a nested loop, jumping out of the nearest inner loop statement

Example 1:

int main() {
	//1. Use break in switch statements
	cout << "Please select the difficulty of your challenge copy:" << endl;
	cout << "1,ordinary" << endl;
	cout << "2,secondary" << endl;
	cout << "3,difficulty" << endl;

	int num = 0;

	cin >> num;

	switch (num)
	{
	case 1:
		cout << "You chose ordinary difficulty" << endl;
		break;
	case 2:
		cout << "You chose medium difficulty" << endl;
		break;
	case 3:
		cout << "You chose difficulty" << endl;
		break;
	}

	system("pause");

	return 0;
}

Example 2:

int main() {
	//2. Using break in a loop statement
	for (int i = 0; i < 10; i++)
	{
		if (i == 5)
		{
			break; //Jump out of loop statement
		}
		cout << i << endl;
	}

	system("pause");

	return 0;
}

Example 3:

int main() {
	//Use break in a nested loop statement to exit the inner loop
	for (int i = 0; i < 10; i++)
	{
		for (int j = 0; j < 10; j++)
		{
			if (j == 5)
			{
				break;
			}
			cout << "*" << " ";
		}
		cout << endl;
	}

	system("pause");

	return 0;
}

4.3.2 continue statement

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

Example:

int main() {

	for (int i = 0; i < 100; i++)
	{
		if (i % 2 == 0)
		{
			continue;
		}
		cout << i << endl;
	}

	system("pause");

	return 0;
}

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

4.3.3 goto statement

**Function: * * can jump statements unconditionally

Syntax: goto tag;

**Explanation: * * if the tag name exists, the goto statement will jump to the location of the tag

Example:

int main() {

	cout << "1" << endl;

	goto FLAG;

	cout << "2" << endl;
	cout << "3" << endl;
	cout << "4" << endl;

	FLAG:

	cout << "5" << endl;

	system("pause");

	return 0;
}

Note: goto statement is not recommended in the program to avoid confusion of program flow

Keywords: C++

Added by indian98476 on Thu, 02 Dec 2021 22:20:42 +0200