[C ++ development plan] Control program flow-judgment and circulation (Day5)

Write in front: Hello everyone! I am [AI Fungus], a programmer who loves to play guitar. Me 热爱AI、热爱分享、热爱开源! This blog is a summary and record of my learning. If you are also 深度学习、机器视觉、算法、Python、C++interested, you can focus on my dynamic, we learn together and progress together -
my blog address is: [AI] bacteria's blog

Previous: [C ++ Development Plan] Operator & Operator Priority (Day4)
Yesterday, we learned the commonly used operators and the priority order of operators in C ++, so that we can flexibly process and transform various data. Today we mainly studyTwo methods of controlling program flow: judgment and circulation



1. Judgment

(1) if… else statement

First of all, we need to think about what needs to be judged? Think about it in real life, we will according to different situations,After judgmentThen go to perform different operations. Then when we use C ++ to solve a problem, we will also encounter this situation. To give a very simple example in mathematics, there is a piecewise function:
and = { 1 ( x > 0 ) 0 ( x 0 ) y=\begin{cases} 1 & (x>0)\\ 0 & (x\le0) \end{cases}
This is a typical example of a sentence that requires judgment. When we want to find y, we must first determine whether x> 0 is true. When the condition is true, we let y = 1; otherwise, let y = 0. Then use if ... else statement to achieve as follows:

if(x>0)
	y=1;  //如果x大于0
else
	y=0;  //如果x小于或等于0

From this, we have a simple understanding of if ... else judgment sentences. So below, let's understand some necessary skills in actual programming!

1.最基本的if...else结构
if(判断条件)
	执行1else
	执行22.当要执行多条语句时,需要用{}将多条语句包含视为一个语句块。
(注意:初学者很容易犯的一个错是,没有加{},这样编译器会默认只执行1if(判断条件)
{
	执行1;
	执行2}
else
	执行33.可以不加else。这种情况下,判断条件为真,则执行12,否则直接跳出判断语句
if(判断条件)
{
	执行1;
	执行2}

4.很重要也是很容易被忽略的一点:判断条件只要不为0(false),就视为真true

(2) Nested if statement

Speaking of nesting, one of the most vivid examples that reminds me is:Matryoshka(It is a wooden doll toy, when you open the doll outside, you will find a smaller doll inside, and then open the doll inside, there are smaller and smaller dolls inside ...)
if statement can also be embedded Set, inside the if statement outside, you can nest an if statement. Of course, the if statement inside can also be nested again. In theory, it can be nested indefinitely. Let ’s take nesting once as an example:

if(判断条件1)
{
	执行1if(判断条件2)
		执行2else
		执行3}
else
	执行4

(3) Multi-branch if statement

Multi-branch if statements are similar to if ... else statements. It's just that the multi-branch statement divides the condition finer, so it will haveThree or moreTake the following piecewise function as an example:
and = { 1 ( x > 0 ) 0 ( x = 0 ) 1 ( x < 0 ) y=\begin{cases} 1 & (x>0)\\ 0 & (x=0)\\ -1 & (x<0) \end{cases}
We use C ++ to implement it as follows:

if(x>0)
	y=1;
else if (x==0)  //注意这个地方要用==,而不是赋值符号=
	y=0;
else
	y=-1;

(4) Switch-case condition processing

In some problems, although you need to make multiple judgment choices, but each time judge the value of the same expression, so there is no need to calculate the value of the expression in every nested if statement A switch statement is provided specifically to solve such problems. The syntax of the switch statement is as follows:

switch(表达式)
{
	case 常量表达式1:语句1;break;
	case 常量表达式2:语句2;break;
	...
	case 常量表达式n:语句n;break;
	default:语句n+1;break;
}

The execution order of the switch statement is: First calculate the value of the expression in the switch statement, then find the constant expression with the same value in the case statement, and use this as the entry to execute the corresponding statement. If no equal constant expression is found, execution starts from default.
Points to note when using switch statements

  • The expression after the switch statement can be integer, character, or enumeration
  • The value of each constant expression cannot be the same, but the order does not affect the execution result.
  • Each case branch can have multiple statements, but do not have to use {}
  • Each case statement is just an entry label, and cannot determine the termination point of execution, so each case branch should be the lastAdd a break statement to end the entire switch structure. Otherwise, it will be executed from the entrance end to the end of the switch structure.

Here is an example, indicating that the entered number (between 1-7) corresponds to the day of the week:

#include<iostream>
using namespace std;
int main()
{
	enum DaysOfWeek  //枚举常量
	{
		Monday=1,
		Tuesday,
		Wednesday,
		Thursday,
		Friday,
		Saturday,
		Sunday
	};
	int day=0;
	cout<<"请输入今天星期几(1-7):";
	cin>>day;
	switch(day)
	{
		case Monday: cout<<"Today is Monday!"; break;
		case Tuesday: cout<<"Today is Tuesday!"; break;
		case Wednesday: cout<<"Today is Wednesday!"; break;
		case Thursday: cout<<"Today is Thursday!"; break;
		case Friday: cout<<"Today is Friday!"; break;
		case Saturday: cout<<"Today is Saturday!"; break;
		case Sunday: cout<<"Today is Sunday!"; break;
		default: cout<<"输入错误,请输入1-7之间的整数"; break; 
	}
	return 0;
}

Here I input 2 from the keyboard, and the output of the
Insert picture description here
program is as follows: Enumeration constants are used in the definition of DaysOfWeek in the program. For students who do n’t know much about it, you can refer to my previous blog: [C ++ development plan] easy to understand-variable scope (Day3)

(5) Use operators? : Conditional processing

C ++ provides an interesting and powerful operator-conditional operator, which is equivalent to a compact if-else structure. The conditional operator is also called the trinocular operator, so it uses three operands.
Here is a simple example, using the operator?: To get the larger of two numbers:

int Max = (num1>num2)? num1:num2;  //判断表达式num1>num2。如果为真,将num1传给Max,否则将num2传给Max

Equivalent to the following if ... else statement:

int Max=0;
if(num1>num2)
	Max=num1;
else
	Max=num2;

If you want to know more about operators, you can poke here: [C ++ Development Plan] Operator & Operator Priority (Day4)

2. Cycle

(1) while loop

Syntax form of while loop:

while(表达式)
{
	循环体;
}

The order of execution is: Determine the value of the expression first, if it is true, continue to execute the loop body statement
Here is a simple example to find the sum of natural numbers 1 to 100.

#include<iostream>
using namespace std;
int main()
{
	int i=1,sum=0;
	while(i<=100)
	{
		sum+=i;
		i++;
	}
	cout<<"sum="<<sum<<endl;
	return 0;
}

The results are as follows:
Insert picture description here

(2) do… while loop

do… while syntax form:

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

The order of execution is: Execute the loop body statement first, and then judge the value of the loop condition expression. When the expression is true, the loop body continues to be executed; otherwise, the loop ends.
Similarly, if the sum of natural numbers 1 to 100 is required, the do ... while structure can also be used, as shown below:

#include<iostream>
using namespace std;
int main()
{
	int i=1,sum=0;
	do{
		sum+=i;
		i++;
	}while(i<=100);
	cout<<"sum="<<sum<<endl;
	return 0;
}

The results are as follows:
Insert picture description here

(3) for loop

The use of the for statement is the most flexible. It can be used both when the number of loops is determined or when the number of loops is unknown. The syntax is as follows:

for(初始语句;表达式1;表达式2)
{
	循环体;
}

The execution flow of the for statement is: First execute the initial statement, and then judge Expression 1 (loop control condition); if it is true, execute the loop body once, otherwise exit the loop. After each execution of the loop body, the value of expression 2 should be calculated first, and then expression 1 should be judged to decide whether to continue the execution of the loop body.
Here is a simple example, we use for () or to achieve the sum of natural numbers 1 to 100.

#include<iostream>
using namespace std;
int main()
{
	int sum=0;
	for(int i=1;i<=100;i++)
	{
		sum+=i;
	}
	cout<<"sum="<<sum<<endl;
	return 0;
}

The results are as follows: the
Insert picture description here
use of for () statement needsNote the following

  • The initial statement, expression 1, expression 2 can be omitted, butThe semicolon cannot be omitted. such as:
for(;;) //相当于while(true)语句,表示将无终止地执行循环体(死循环) 
  • Expression 1 is the loop control condition. If omitted, the loop will continue without termination.
  • When the initial expression statement is a statement statement, it can contain multiple variable statements, separated by commas. such as:
for(int i=0,j=10; i<=j; i++,j--) k=i+j;

(4) The use of continue and break

  1. break statement. Appears in the swtch statement or loop body structure, so that the program jumps out of the entire loop body and switch statement, and continues to execute the next logical statement. The break statement is not suitable for other occasions.
  2. continue. Can appear in the circulation body, its role isEnd this cycle(That is, skip the following code in the loop block); then re-judge the loop condition and decide whether to continue to execute the next loop.

(5) Immature goto

The form of goto syntax is as follows:

JumpToPoint:
	循环体;
	goto JumpToPoint; //转跳回JumpToPoint处,重新执行循环体

What needs to be explained here is: because the goto statement is not structural, its frequent use will make the program confusing, soIt is not recommended to use it

Published 61 original articles · Like 776 · Visitors 20,000+

Guess you like

Origin blog.csdn.net/wjinjie/article/details/105646675