Branch structure and loop structure of zero-based C language

1. Branch structure

1.if statement

2.if-else statement

3. Multiple if-else statements

4. Nested if-else statements

2. Cycle structure

1. while loop

2.do-while loop

for loop

Comparison of Three Loop Structures

Multiple loops in loop structure

3. End statement

1.break statement

2. continue statement

4. Branch structure

1. switch statement

Five, goto statement

6. Multi-instance test

————————————————————————————————————————————
1. Branch structure
1.
The basic structure of the if statement :
The if statement judges a condition. When the condition is true, {}the statement being executed is executed; otherwise, the statement is not executed.
The syntax of the if statement is as follows:

if(表达式)
{
    
    
	执行代码块;
}

Note: Do not add a semicolon at the end, and directly add 2. if-else statementif() after it. The if-else statement judges a condition. When the condition is true, one operation is performed, otherwise another different operation is performed. The syntax of the if-else statement is as follows:{}


if(表达式)
{
    
    
	语句1}
else
{
    
    
	语句2}

Note:
(1) There is no semicolon after if()! If you accidentally add a semicolon at the end, there will be a grammatical error, and the error message will point to else: illegal else, there is no matching if (
2) If there is only one sentence after the if and else, it can be removed {}. When the statement exceeds When there are two sentences, it must be added {}. Adding curly braces can clearly indicate the scope of control of if or else.
3. Multiple if-else statements
Multiple if-else statements judge the value of the expression in turn. When the value of an expression is true, the operation corresponding to the expression is executed, otherwise the operation corresponding to the else is executed.
The syntax format of multiple if-else statements:

if(表达式1{
    
    
	语句1}
else if(表达式2{
    
    
	语句2}
……
else if(语句m)
{
    
    
	语句m;
}
else
{
    
    
	语句n;
}

Note: When an expression is true, other statements of the branch structure will not be executed downward.
4. Nested if-else statements
Usually an if-else statement is placed inside another if-else statement to form a nested if-else statement.
The syntax format of nested if-else statements:

if(表达式1{
    
    
	if(表达式2{
    
    
		语句2}
	else
	{
    
    
		语句3}
}
else
{
    
    
	语句4}

2. Loop structure
In the C language, the repeated execution of an action is what we often call a loop. The C language provides loop statements to achieve repeated processing. In C language, each loop has a control expression, and each time the loop body is executed, the control expression is evaluated, and if the expression is non-zero, the loop continues to execute. There are three kinds of loop statements in C language, namely while statement, do statement and for statement. The while loop tests the control expression before executing the loop body, the do loop tests the control expression after the loop body executes, and the for loop is very suitable for those loops that specify the number of iterations.
1. while loop
The while loop is suitable for performing an operation repeatedly if a certain condition is true, so the while statement is the simplest and easy to use.
The general format of the while statement is as follows

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

Function: When the expression value is not 0, execute the loop body statement repeatedly.
Execution process: first calculate the value of the expression in parentheses, if the value is not 0, then continue to execute the statement of the loop body, and then judge the expression. This process continues until the expression evaluates to 0.
Next, look at a classic question using a while loop:
/*Program: Use a while loop to find the sum of 10 integers*/

#include<stdio.h>
int main(void)
{
    
    
	int i,number,sum;/*number用来暂存读入的整数,sum存储累加和*/
	sum=0;/*sum赋值为0*/
	i=1/*循环变量i赋值为1*/
	printf("请输入10个整数:\n");
	while(i<=10)   /*循环条件是i不大于10*/
	{
    
    
		scanf("%d",&number);/*读入一个整数存入number*/
		sum+=number;/*number累加到变量sum中*/
		i=i+1;/*循环变量i增加1,也可以写成i++*/
	}
	printf("累加和为:%d\n",sum);/*输出累加和*/
	return 0}

Note:
(1) Since the floating-point number of the computer is only an approximate value, an inaccurate value may be obtained by using a floating-point number as a loop control variable, which may lead to an error in the test of the loop termination condition, so an integer value should be used to control the technical loop .
(2) Indent the internal statement controlled by the control statement header, and leave blank lines before and after the control statement, which can make the program have a two-dimensional sense of hierarchy and greatly improve the readability of the program.
(3) If in the loop body of the while loop, there is no operation that finally changes the condition to false, then the loop will never terminate-this is the so-called infinite loop (that is, an infinite loop).
2. The do-while loop
The do-while loop is to execute the statement in the loop first, and then judge whether the expression in the while is true, if it is true, continue the loop; if it is false, terminate the loop. Therefore, the do-while loop must execute the loop statement at least once.
The general format of a do-while statement is as follows:

do
{
    
    
	语句1}while(表达式);//切记,这里有分号。

Note: When using the do-while statement, a semicolon must be added after the parentheses of while.

3. for loop
The for loop statement can handle all the details of the count control. It is the most powerful loop statement and the best way to write many loops.
The standard format of the for statement is as follows:

for(表达式1;表达式2;表达式3{
    
    
	语句;
}

Execution process:
(1) Execute expression 1, initialize the loop variable, and execute it only once.
(2) Judgment expression 2, if its value is true (not 0), then execute the statement in the for loop, and then execute downward; if its value is false (0), then end the loop.
(3) The last operation executed in each loop. Set the step size of the loop and change the value of the loop variable, thereby changing the truth or falsehood of the expression 2.
(4) When the loop ends, the program executes downward.
In most cases, the above for statement can be expressed as the following while statement

表达式1
while(表达式2)
{
    
    
	语句;
	表达式3}

In the for loop:
(1) Expression 1 is one or more assignment statements, which are used to control the initial value of the variable;
(2) Expression 2 is a relational expression, which decides when to exit the loop;
(3) The expression is the step value of the loop variable, which defines how the loop variable changes after each loop.
(4) These three parts are separated by semicolons; remember not to write commas.
Precautions for the for statement:
(1) The three expressions in the for statement header: initialization, loop continuation condition and increment operation can all contain arithmetic expressions
For example:

for(i=m+1;i<=4*n;i+=n/m)

(2) The increment of the control variable can be negative, in which case the loop count is decremented.
For example, the function of the following program segment is to "count down" information

for(i=10;i>0;i=i-1)
{
    
    
	printf("%d ",i);
}

(3) The three expressions in the for statement are optional. If expression 2 is omitted, the loop continuation condition is assumed to be always true, which results in an infinite loop. If the initialization of the loop control variable has already been done elsewhere in the program, then expression 1 can be omitted. Expression 3 can also be omitted if the increment of the loop control variable is done by the statement in the body of the for loop, or if no increment is required at all. The increment expression in the for loop statement can be replaced by a single statement at the end of the loop body.
(4) Expression 1 and Expression 3 can be a simple expression or multiple expressions separated by commas

int sum,num;
for(sum=0,num=0;num<=3;num++,sum++)
{
    
    
	sum+=num;
	printf("num=%d,sum=%d\n",num,sum);
}

(5) If the scope of the loop is more than one statement, it must be added to {}form a compound statement, which is easy for beginners to forget {}, resulting in mistakes.
For example:

for(i=1;i<=n;i++)
	scanf("%d",&number);
	sum+=number;

Then it is equivalent to the following program segment

for(i=1;i<=n;i++)
{
    
    
	scanf("%d",&number);
}
sum+=number;`

The statement sum+=number is outside the loop body.
(6)
If you accidentally add a semicolon after the parentheses of the for loop, an empty statement will be created, and the compiler will think that the content of the loop is the empty statement.

for(i=1;i<=n;i++)
{
    
    
	scanf("%d",&number);
	sum+=number;
}

This statement is equivalent to:

for(i=1;i<=m;i++)
{
    
    
	;
}
scanf("%d",&number);
sum+=number;

This statement is interpreted by the compiler as a loop body, and the loop body understood by the designer is understood by the compiler as the follow-up statement of the loop statement. After the loop ends, it is only executed once.
(7) Loop control variables, in addition to being used to control the loop, can also be used in the calculation of the loop body. However, it is best not to change the value of the loop control variable in the for loop, which may cause some hidden errors.

The three kinds of loops in the loop structure compare
while, do-while, and for. There are differences in the specific usage scenarios:
1. It is more suitable to use the for loop when the number of loops is known.
2. It is suitable when the number of loops is not known. Use while or do-while
(1) If it is possible not to loop once, consider using a while loop
(2) If there is at least one loop, consider using a do-while loop

Multiple loops of loop structure
Multiple loops are loop structures that appear in loop structures,
but in actual development, up to three layers of multiple loops are used

Because the more loop layers, the longer the running time, the more complex the program, so at most 2-3 layers of multiple loops are used. In addition, different loops can also be nested.

During the execution of multiple loops, the outer loop is the parent loop and the inner loop is the child loop.

Once the parent loop is executed, all the sub-loops will be executed until the sub-loop is exited. The parent loop enters the next time, and the child loop continues to execute...

#include<stdio.h>
int main(void)
{
    
    
	int i,j,k;
	for(i=1;i<5;i++)
	{
    
    
	//观察每行空格数量,补全循环条件
		for(j=1;j<5;j++)
		{
    
    
			printf(" ");//输出空格
		}
		for(k=0;k<2*i-1;k++)
		{
    
    
			printf("*");//每行输出*号
		}
		printf("\n");//每次循环之后换行,打印下一行
	}
	return 0;
}

3. End statement
1.break statement
The break statement is generally used to exit the loop or jump out of the switch statement early. Executing the break statement will cause the program to immediately jump out of these statements and go to the next statement immediately following.
For example, go to the playground for a run and plan to run 10 laps, but during the run, if you feel unwell, you can end the run early and go back to rest. The above
situation can be expressed as logic

for(i=1;i<=10;i++)
{
    
    
	if(感到身体不适)
	break;
}

breakPay attention to the following points when using statements
1. In the absence of a loop structure, break cannot be used in a single if-else statement.
2. In multiple loops, a break statement can only jump out of one level of loop and can only be the current loop.

2. Continue statement
Use the continue statement to interrupt the current execution of the loop body (that is, skip the statement that has not been executed in the loop body), and start a new round of loop immediately.
The difference between the break statement and the continue statement is:
the break statement is to jump out of the current entire loop, and the continue statement is to end this loop and start the next loop.

4. Branch structure
1. switch statement
When the problem needs to deal with many branches (generally more than 3), switch statements are usually used instead of conditional statements to simplify program design. The switch statement is like a multi-way switch, which makes the program control flow form multiple branches, and selects one or several branches to execute according to the different values ​​of an expression. The switch statement in C language is also called switch statement.
The most common format for a switch statement:

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

A switch statement tends to be easier to read than a multibranch if statement. In addition, the switch statement tends to execute faster than the if statement, especially when there are many conditions to be determined.
Note:
(1) The values ​​of each constant expression after the case cannot be the same, otherwise an error will occur
(2) After the case, if there is no break, it will continue to execute until a break is encountered before jumping out of the switch statement
(3) After the switch The expression statement of can only be of integer or character type.
(4) After the case, multiple statements are allowed without {}enclosing them
(5) The order of each case and default statement can be changed without affecting the execution result of the program.
(6) The default statement can be omitted.
The application of switch and if statement
calculates the day of the year

#include<stdio.h>
int main(void)
{
    
    
	int date=0;
	int year=2008;
	int month=8;
	int day=8;
	switch(month)
	{
    
    
		case 12 :date+=30;
		case 11 :date+=31;
		case 10 :date+=30
		case 9 :date+=31
		case 8 :date+=31
		case 7 :date+=30
		case 6 :date+=31
		case 5 :date+=30
		case 4 :date+=31
		case 3 :
		if(year%4==0&&year%100!=0||year%400==0)
		{
    
    
			date+=29;
		}
		else
		{
    
    
			date+=28;
		}
		case 2:date+=31;
		case 1:date+=day;
		printf("%d年%d月%d日是该年的第%d天“,year,month,day,date);
		break;
		default:
		printf("error");
		break;
	}
	return 0;
}

Five, goto statement
The goto statement in C language is an unconditional branch statement, and the goto statement can jump to any labeled statement in the function. The goto statement is an ancient statement, the predecessor of the loop statement. In the early days of computer development, programs consisted of several statements + statement labels + jump statements.
Format of the goto statement

goto 语句标号;

Statement label: A statement label consists of an identifier plus a colon, which identifies a specific location in the program, and is generally placed on the left side of an executable statement.
Function: Convert the program to the specified position to continue execution.
How does the goto statement implement a loop? Take the cumulative sum of 1-100 as an example:

sum=0,i=1;
loop:sum=sum+1;
i++;
if(i<=100)//如果i<=100,跳转到loop处,从而实现循环
	goto loop;
printf("%d\n",sum);

The goto statement is usually not used, mainly because it will destroy the structure of the program, and it is not easy to read, and it is easy to bring hidden dangers. But when you need to exit from multiple loops, or loops that contain switch statements, it is more reasonable to use the goto statement.

The above is the explanation of the branch structure and loop structure of C language. I hope my article can help you who are learning C language. As the saying goes, practice is the only criterion for testing truth, and I hope you can try to write some topics about branch structure and loop structure by yourself to deepen your understanding of this article. May you all learn something! I hope that my friends who like me will pay attention to it and comment a lot, thank you! ! !

Guess you like

Origin blog.csdn.net/z2004cx/article/details/128196808