Systematic and intensive lectures on C language (6): C language selection structure and loop structure

There are three major structures in C language, namely sequence structure, selection structure and loop structure:

  1. The C language sequential structure allows the program to execute each C language code in order from beginning to end, without repeating any code or skipping any code.
  2. The C language selection structure is also called the branch structure, which allows the program 拐弯, to selectively execute the code; in other words, it can be skipped Useless code, only execute useful code
  3. The C language loop structure allows the program 杀个回马枪, to repeatedly execute the same piece of code.

The sequential structure is easy to understand, and there is no need to say more. This article focuses on the selection structure and loop structure.

1. C language selection structure

When we were children, our parents told us to remember this sentence红灯停,绿灯行,黄灯等待, which means the status of the traffic light. When the traffic light is red, it means to stop. When the light is green, it means you can walk; when it is yellow, you need to wait. Next, use code to simulate the traffic light situation at this time. The specific code is as shown below:
Insert image description here
As you can see from the code, there are purple if statements. The blue else if sentences and the red else sentences are unfamiliar words, so this article will explain what they mean one by one. if statement: that is, conditional judgment if statement. if The result of the conditional expression in the brackets is , and the statement in the curly brackets below if is executed. else if statement: that is, conditional judgment else if statement. else if The result of the conditional expression in the brackets is , and the statement in the curly brackets below else if is executed. else statement: that is, conditional judgment else statement. When the conditional expression results of the if and else if statements are both , execute the following else statement in braces. The above is a brief introduction to the functions of these three conditional judgment statements. Next, we will introduce the conditional control statements in detail.

1.1 if statement

The if statement judges the expression and decides whether to perform the corresponding operation based on the result of the judgment. For example, as shown in the picture below, buy a lottery ticket, and if you win, buy a car.
Insert image description here
The winning flow chart is shown below:
Insert image description here
The general form of the if statement is:

if(表达式)
语句;

The execution flow chart of the if statement is shown below:
Insert image description here
For example, the following line of code:

if(iNum)
//代码中判断变量iNum的值,如果变量iNum为真值,则执行后面的输入语句;如果变量的值为假,则不执行后面的输入语句
printf("这是真值");

In the parentheses of the if statement, you can not only judge whether the value of a variable is true, but also whether the result of the expression is true, for example:

if(iSignal==1)
//判断变量iSignal==1的表达式,如果条件成立,那么判断的结果是真值,则执行后面的输出语句
//如果条件不成立,那么结果为假值,则不执行后面的输出语句
printf("当前信号灯的状态是:%d:",iSignal);

From the above two lines of code, you can see that the execution part after if only calls one statement. What if there are two statements? At this time, you can use curly brackets to enclose the execution part to make it a statement block, for example:

if (iSignal == 1) {
    
    
    printf("当前信号灯的状态是:%d:\n", iSignal);
    printf("车需要停止");
}

Put the executed statements in curly brackets, so that when the if statement determines that the condition is true, all of them can be executed. The advantage of using this method is that the range of statements contained in the if statement can be more standardized and clearly expressed. Therefore, it is recommended that everyone use curly brackets to include the execution statement when using the if statement.

1.2 if…else statement

In addition to specifying certain statements to be executed when the condition is true, you can also execute another piece of code when the condition is false. This is done using else statements in C language, for example: buy lottery tickets, if you win, buy a car, otherwise buy a bicycle, as shown in the figure below:
Insert image description here
The corresponding process The figure is as shown below:
Insert image description here
if…else The general form of the statement is:

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

if…elseThe execution flow chart of the statement is as shown below:
Insert image description here
The result of the expression is judged in the brackets after the if. If the result of the judgment is true, the execution follows the if The contents of the statement block; if the result of the judgment is false, the contents of the statement block after the else statement will be executed. For example:

if (value) {
    
    
	printf("这个值为真");
} else {
    
    
	printf("这个值为假");
}

In the above code, if if determines that the value of variable value is true, the statement block following if is executed for output. If the result of the if judgment is false, the statement block below the else is executed.

Note: An else statement must follow an if statement.

1.3 else if statement

The else if statement can be implemented by using the combination of if and else keywords, which tests a series of mutually exclusive conditions. For example, a 4S store conducts a big wheel lottery, and you can get different types of cars based on the winning amount. The winning amount ranges are mutually exclusive. Only one amount range can appear in each lottery result, as shown in the figure below. :
Insert image description here
To implement this lottery process, you can use the else if statement. The corresponding flow chart is shown below:
Insert image description here
The general form of else if statement is as follows:

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

The execution flow chart of the else if statement is shown below:
Insert image description here
According to the flow chart, the expression 1 in the if statement is first judged. If the result is true, then Execute the following statement 1, and then skip the else if statement and the else statement; if the result is false, then evaluate the expression 2 in the else if statement. If expression 2 is true, then statement 2 is executed without executing the subsequent else if judgment or else statement. When all judgments are false, that is, they are all false, the statement block after else is executed. For example:

if(iSelection==1)
    {
    
    }
else if(iSelection==2)
    {
    
    }
else if(iSelection==3)
    {
    
    }
else
    {
    
    }

The meaning of the above code is:

  1. Use the if statement to determine whether the value of the variable iSelection is 1. If it is 1, execute the content in the subsequent statement block, and then skip the subsequent else if statement judgment and execution of the else statement.
  2. If the value of iSelection is not 1, then the else if statement determines whether the value of iSelection is 2. If the value is 2, the condition is true, and the following statement block is executed. After execution, the following else if statement and else are skipped. Statement operations.
  3. If the value of iSelection is not 2, then the following else if statement determines whether iSelection is equal to the value 3. If it is equal to 3, the content in the following statement block is executed, otherwise the content in the else statement block is executed. That is to say, when all the previous judgments are not true (are false values), the content in the else statement block is executed.

1.4 Nesting of if statements

Nesting can be understood as mosaic and application, such as the familiar Russian matryoshka dolls, one layer inside another. This practice is called nesting. Then, if nesting means that one or more if statements can be included in the if statement. The general form is as follows:

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

The function of using if statement nesting is to refine the conditions for judgment and then perform corresponding operations. Example: In life, when people wake up every morning, they think about what day of the week it is. If it is the weekend, it is a day off. If it is not the weekend, it is a day off. Work; at the same time, the rest day may be Saturday or Sunday. On Saturday, I go shopping with my friends, and on Sunday, I spend time with my family at home. The specific code is as follows:

#include<stdio.h>

int main() {
    
    

  int iDay;    //定义变量表示输入的星期几
  //定义变量代表一周中的每一天
  int Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4,
      Friday = 5, Saturday = 6, Sunday = 7;
  printf("请选择星期几:\n");               //提示信息
  scanf("%d", &iDay);                       //输入星期
  if (iDay > Friday)                        //休息日的情况
  {
    
    
    if (iDay == Saturday)                 //为周六时
    {
    
    
      printf("和朋友去逛街\n");
    } else                                    //为周日时
    {
    
    
      printf("在家陪家人\n");
    }
  } else                                       //工作日的情况
  {
    
    
    if (iDay == Monday)                //为周一时
    {
    
    
      printf("开会\n");
    } else                          //为其他星期时
    {
    
    
      printf("工作\n");
    }
  }
  return 0;                        //程序结束
}

The program execution result is shown in the figure below:
Insert image description here
The entire code represents the entire if statement nested operation process. First, it is judged to be a rest day, and then the selection is made based on the judgment result. Corresponding specific judgment or operation. The process is as follows:

  1. The if statement evaluates expression 1 just like it determines what day of the week it is today. Assuming that the judgment result is true, the if statement is used to evaluate expression 2.
  2. For example, determine that today is a rest day, and then determine whether today is Saturday; if the if statement determines that iDay==Saturday is true, then execute statement 1. If not true, then statement 2 is executed.
  3. For example, if it’s Saturday, go shopping with your friends; if it’s Sunday, go home with your family. The outer else statement indicates the corresponding operation when it is not a holiday.

1.5 Conditional operators

The auto-increment, auto-decrement and compound assignment operators are all streamlined operators provided by the C language. Conditional selection also provides a streamlined operator - the conditional operator (also known as the ternary operator). A conditional operator is a conditional expression formed by connecting three expressions together. The syntax format of conditional operators is as follows:

返回值=表达式1?表达式2:表达式3;

The meaning of the above statement is: first test the value of expression 1. If the value is true, the return value is the result value of expression 2. If the value is false, the return value is the result value of expression 3. Sample code:

b=a>2?2:3;

The operation process of this statement is shown in the figure below:
Insert image description here
This code is equivalent to:

if(a>2)
{
    
    
   b = 2;
}
else
{
    
    
   b = 3;
}

Simulate the conditional operator to implement Meituan's food delivery situation. If it meets 15 yuan, the delivery will be free. Otherwise, a 5 yuan delivery fee will be added. The implementation code is as follows:

#include<stdio.h>

int main() {
    
    
  int food, fee;//定义变量存储餐费、总共费用
  printf("您的订单餐费是:\n");//提示信息
  scanf("%d", &food);//输入餐费
  fee = food >= 15 ? food : (food + 5);//利用三目运算符计算总共费用
  printf("您的订单共计%d元,请支付\n", fee);//输出总共费用
  return 0;//程序结束
}

The program running result is as shown below:
Insert image description here

1.6 Basic form of switch statement

The if statement only has two branches to choose from, but in practical problems it is often necessary to use multiple branches. Just like buying clothes, there are many options to choose from. Of course, using nested if statements, you can also use multiple branches to realize the choice of buying clothes. However, if there are more branches, there will be more layers of nested if statements, making the program redundant and poor readability. In C language, you can use the switch statement to directly handle multi-branch choices such as buying clothes to improve the readability of the program code. The switch statement is a multi-branch selection statement, and its general form is as follows:

switch(表达式)
{
    
    
   case1:
       语句块1;
   case2:
       语句块2;
   case 值n:
       语句块n;
   default:
   		//default部分被省略后,当控制台输入的值与case语句后的值均不能匹配时,程序没有输出任何结果
       都不符合语句块;
}

The program flow of the switch statement is shown in the figure below:
Insert image description here
Analyze the general form of the switch statement through the flow chart shown in the figure above. The expression in parentheses after the switch statement is the condition to be judged. In the statement block of the switch, the case keyword is used to indicate various situations where the test conditions are met. The subsequent statements are the corresponding operations. There is also a default keyword, which is used to execute default if there is no condition that meets the conditions. The default statement.

Note: The condition tested by the switch statement must be an integer expression, which means it can also contain operators and function calls. The value tested by the case statement must be an integer constant, that is, it can be a constant expression or constant operation.

Let’s analyze how to use the switch statement through the following code:

#include<stdio.h>

int main() {
    
    
  int selection = 1;
  switch (selection) {
    
    
    case 1:printf("选择矿泉水\n");
      break;
    case 2:printf("选择旺仔\n");
      break;
    case 3:printf("选择脉动\n");
      break;
    default:printf("输入错啦!\n");
      break;
  }
}

The switch determines the value of the selection variable, and uses the case statement to check different situations of the selection value. Assume that the value of selection is 1, then when case is executed as 1, it will output选择矿泉水, and after execution, break will jump out of the switch statement; assuming that the value of selection is 2, it will output 选择旺仔, after execution, break will jump out of the switch statement; assuming the value of selection is 3, it will output 选择脉动, after execution, break will jump out of the switch statement; if the value of selection is not the column tested in the case If the statement in default is executed, 输入错啦! will be output. There is a break keyword after every case or default statement. The break statement is used to jump out of the switch structure and no longer execute the code below the switch.

Note: When using the switch statement, if none of the values ​​following the case statement can match the conditions of the switch statement, the code following the default statement will be executed. No two case statements can use the same constant value; and each switch structure can only have one default statement, and default can be omitted.

When using the switch statement, a break statement must be used in each case. The break statement causes the switch statement to be jumped out after the case statement is executed. If there is no break statement, the program will execute all subsequent content. For example, in the following code, no break is added after the case statement. The code is as follows:

#include<stdio.h>

int main() {
    
    
  int money = 0;
  printf("请查看口袋剩多少元钱?\n");
  scanf("%d", &money);
  switch (money) {
    
    
    case 7:printf("还剩%d元,吃米饭套餐\n", money);
      //没有break语句
    case 12:printf("还剩%d元,吃米线\n", money);
      //没有break语句
    case 40:printf("还剩%d元,吃披萨\n", money);
      //没有break语句
    default:printf("没钱了,你可别吃了!!!\n");
  }
}

The program running result is as shown in the figure below:
Insert image description here
As can be seen from the above figure, after removing the break statement, all statements after the case test are output. Therefore, if you want to output a selected case, the break statement is indispensable in the case statement.

1.7 Switch statement in multi-way switch mode

In the previous section, after removing the break statement, all statements that meet the test conditions will be output. Taking advantage of this feature, you can design a switch statement in multi-way switch mode. Its form is as follows:

switch(表达式)
{
    
    
  case 1:
    语句1;
    break;
  case 2:
  case 3:
    语句2;
    break;
  default:
    默认语句;
    break;
}

It can be seen from the form that if the break statement is not used after case 2, the effect when the test is met is the same as when the test of case 3 is met. In other words, using the multi-way switch mode, multiple test conditions can be output with one statement block. For example: In a normal year, there are 12 months in a year, January, March, May, July, August, October, and December have 31 days, April, June, September, and November have 30 days, and February has 28 days. If in the console Enter any month on the page and you will know how many days there are in this month. The specific code is as follows:

#include<stdio.h>
int main() {
    
    
  int month;
  printf("请输入月份:\n");
  scanf("%d", &month);
  switch (month) {
    
    
    //多路开关模式
    case 1:
    case 3:
    case 5:
    case 7:
    case 8:
    case 10:
    case 12:printf("%d月有31天\n", month);
      break;
      //多路开关模式
    case 4:
    case 6:
    case 9:
    case 11:printf("%d月有30天\n", month);
      break;
    case 2:printf("%d月有28天\n", month);
      break;
    default:printf("输入错啦,没有这个月份\n");
  }
  return 0;//程序结束
}

The program running result is as shown below:
Insert image description here

1.8 The difference between if…else statement and switch statement

if...else statements and switch statements are both used to test conditions and make corresponding judgments based on different situations. The flow charts of the two are shown below:
Insert image description here
Insert image description here
The following is a comparison of the syntax and efficiency of the two to explain the difference between the two:

  1. Comparison of syntax. The if statement is used with the else keyword, and the switch statement is used with the case statement; the if statement first judges the condition, and the switch statement makes the judgment later, that is, the judgment is consistent with the case statement situation.
  2. Comparison of efficiency. The if...else structure is faster for a small number of tests at the beginning, but will gradually slow down as the tests grow, and the default case is the slowest. Expressions can be judged using the if else structure, but it is not easy to add and expand later. In the switch structure, the speed of each case test is the same, and the default case is faster than other cases. When the number of cases to be determined is in the minority, the if...else structure is faster to check than the switch structure. In other words, if there are less than 3 or 4 branches, it is better to use the if...else structure, otherwise choose the switch structure.

2. C language loop structure

Provident fund is deposited by state agencies, state-owned enterprises, urban collective enterprises, foreign-invested enterprises, urban private enterprises and other urban enterprises, institutions, private non-enterprise units, social groups (hereinafter collectively referred to as units) and their employees. of long-term housing savings. The interest rate of a provident fund loan to buy a house is much lower than that of a commercial loan, which can leave a lot of money for the house buyer. Therefore, if employees have a provident fund, they will choose to use a provident fund loan to buy a house. This example simulates buying a house with provident funds and calculating the monthly payment required. The specific code is as follows:
Insert image description here
As you can see from the code, there are many familiar words, such as double,scanf,printf and there are many operator calculations, etc. In addition, there is for in the red box. Let’s take a brief look at it next.

  1. Three i: are the conditions of the loop statement. The first i is the initial value of the loop; the second i is the length of the loop; the third i is the change< /span>. i, let the changed value be compared with the second i
  2. Braces {}: is the loop statement block 分割标志. The loop part is the statement block in the curly brackets {}, which is the code sum*=1.049.

The above is a brief introduction to the usage offor statement. The specific usage offor statement will be explained in detail in the following sections. Of course, except for < /span>for In addition to loop control statements, there are other loop statements. Next, we will explain in detail how to use each loop statement and the corresponding flow chart.

2.1 Detailed explanation of while loop and do while loop in C language

2.1.1 while loop

The general form of a while loop is:

while(表达式){
    
    
    语句块
}

means, first calculate the value of 表达式, when the value is true (non-0), Execute语句块; After execution语句块, calculate the value of the expression again. If it is true, continue execution语句块... This process will Repeat until the value of the expression is false (0), exits the loop and executes the code after while. The flow of while statement execution is shown in the figure below:
Insert image description here
We usually call 表达式 the loop condition and 语句块 the loop body , the entire loop process is a process of constantly judging the loop conditions and executing the loop body code.

Use a while loop to calculate the value of 1 added to 100:

/*================================================================
*   Copyright (C) 2023 AmoXiang All rights reserved.
*   
*   文件名称:06-while.c
*   创 建 者:AmoXiang
*   创建日期:2023年10月16日 16:26:05
*   描    述:
*
================================================================*/


#include <stdio.h>
int main(){
    
    
    int sum = 0, i = 1;
    while(i<=100){
    
    
        sum += i;
        i++;
    }
    printf("1-100的和为:%d\n", sum);
}

The program running result is as shown below:
Insert image description here
Code analysis:

  1. When the program runs to while, because i=1 and i<=100 are true, the loop body will be executed; after the execution, the value of i changes to 2 and the value of sum changes to 1.
  2. Next, it will continue to determine whether i<=100 is true, because at this time i=2, i<=100 is true, so the loop body continues to be executed; after the execution, the value of i changes to 3, and the value of sum changes to 3.
  3. Repeat step 2.
  4. When the loop proceeds to the 100th time, the value of i changes to 101 and the value of sum changes to 5050; because i<=100 is no longer true at this time, the loop is exited, the loop body is no longer executed, and the remainder of the while loop is executed. code.

The overall idea of ​​the while loop is this: Set a loop condition with variables, that is, an expression with variables; add an additional statement to the loop body so that it can change the value of the variable in the loop condition. In this way, as the loop continues to execute, the values ​​of the variables in the loop condition will continue to change. There will eventually be a moment when the loop condition is no longer true and the entire loop ends.

What happens if the loop condition contains no variables?

If the loop condition is true, the while loop will continue to execute and never end, becoming 死循环. For example:

/*================================================================
*   Copyright (C) 2023 AmoXiang All rights reserved.
*   
*   文件名称:07-while.c
*   创 建 者:AmoXiang
*   创建日期:2023年10月16日 16:33:07
*   描    述:
*
================================================================*/

#include <stdio.h>
int main(){
    
    
    while(1){
    
    
    	//运行程序,会不停地输出1,直到用户强制关闭。
        printf("1\n");   
    }
    return 0;
}

If the loop condition is not established, the while loop will not be executed even once. For example:

#include <stdio.h>
int main(){
    
    
    while(0){
    
    
     	//运行程序,什么也不会输出
        printf("1\n");
    }
    return 0;
}

2.1.2 do-while loop

In addition to the while loop, there is also a do-while loop in C language. The general form of a do-while loop is:

do{
    
    
    语句块
}while(表达式);

The difference between the do-while loop and the while loop is that it will first execute 语句块, and then determine whether the expression is true. If so If true, the loop continues; if false, the loop is terminated. Therefore, the do-while loop must be executed at least once 语句块.

Example: Use do-while to calculate the value of 1 added to 100.

/*================================================================
*   Copyright (C) 2023 AmoXiang All rights reserved.
*   
*   文件名称:09-do-while.c
*   创 建 者:AmoXiang
*   创建日期:2023年10月16日 16:45:27
*   描    述:
*
================================================================*/


#include <stdio.h>
int main(){
    
    
    int i = 1, sum = 0;
    do{
    
    
        sum += i;
        i++;
    }while(i <= 100);
    printf("1-100的和为:%d\n", sum);
    return 0;    
}

The program running result is as shown below:
Insert image description here
Note: When using the do...while statement, the loop condition must be placed after the while keyword In the brackets, a semicolon must be added at the end, which many beginners tend to forget.
Insert image description here
While loop and do-while have their own characteristics, you can choose appropriately. In actual programming, while loop is used more often.

2.2 Detailed explanation of for loop (for statement) in C language

2.2.1 Basic use

In addition to the while loop, there is also a for loop in C language, which is more flexible in use and can completely replace the while loop.

#include <stdio.h>
int main(){
    
    
    int i, sum=0;
    i = 1;  //语句①
    while(i<=100 /*语句②*/ ){
    
    
        sum+=i;
        i++;  //语句③
    }
    printf("%d\n",sum);
    return 0;
}

It can be seen that statements ①②③ are placed in different places, and the code structure is relatively loose. To make the program more compact, you can use a for loop instead, as shown below:

#include <stdio.h>
int main(){
    
    
    int i, sum=0;
    for(i=1/*语句①*/; i<=100/*语句②*/; i++/*语句③*/){
    
    
        sum+=i;
    }
    printf("%d\n",sum);
    return 0;
}

In the for loop, statements ①②③ are grouped together, and the code structure is clear at a glance. The general form of a for loop is:

for(表达式1; 表达式2; 表达式3){
    
    
    语句块
}
//执行过程为:
//(1)先执行 表达式1
//(2)再执行 表达式2,如果它的值为真(非0),则执行循环体,否则结束循环
//(3) 执行完循环体后再执行 表达式3
//(4)重复执行步骤 (2) 和 (3),直到 表达式2 的值为假,就结束循环。

//上面的步骤中,(2) 和 (3) 是一次循环,会重复执行,for 语句的主要作用就是不断执行步骤 (2) 和 (3)。

表达式1 is only executed during the first loop and will not be executed again in the future. This can be considered an initialization statement. 表达式2 is generally a relational expression that determines whether to continue the next cycle, called 循环条件. 表达式3 is often an expression with an increment or decrement operation so that the loop condition gradually becomes 不成立. The execution process of the for loop can be represented by the following figure:
Insert image description here
Let’s analyze the code of 计算从1加到100的和 again:

#include <stdio.h>
int main(){
    
    
    int i, sum=0;
    for(i=1; i<=100; i++){
    
    
        sum+=i;
    }
    printf("%d\n",sum);
    return 0;
}

Code analysis:

  1. When executing the for statement, first assign i an initial value of 1 and determine whether i<=100 is true; because i=1 and i<=100 are true at this time, the loop body is executed. After the execution of the loop body ends (the value of sum is 1), i++ is calculated again.
  2. During the second loop, the value of i is 2, i<=100 is established, and the loop body continues to be executed. After the execution of the loop body ends (the value of sum is 3), i++ is calculated again.
  3. Repeat step 2 until the 101st loop. At this time, the value of i is 101, and i<=100 is not true, so the loop ends.

From this we can summarize the general form of the for loop:

for(初始化语句; 循环条件; 自增或自减){
    
    
    语句块
}

2.2.2 Variations of for loop

From the study in Section 2.1, we can see that there are three expressions in the general form of the for statement. In the actual program writing process, these three expressions can be omitted according to the situation. Next, different situations will be explained.

(1) Omit expression 1 in the for statement

The function of the first expression in the for statement is to set the initial value of the loop variable. If you omit expression 1 in the for statement, you need to assign a value to the loop variable before the for statement. The sample code for omitting expression 1 in the for statement is as follows:(2) Omitting expression 2 in the for statement
Insert image description here

If expression 2 is omitted, that is, the loop condition is not judged, the loop will continue without termination, that is, the default expression 2 is always true. For example: (3) Omit expression 3 in the for statement
Insert image description here

Expression 3 can also be omitted. For example:

int number;
for(number=1; number<=20;) // 省略表达式3
{
    
    
	sum=sum+ number;
}

This code does not change the value of the number variable, and the loop will continue without termination. If you want the program loop to end normally, change the code to the following form:

int number;
for(number=1; number<=20;) // 省略表达式3
{
    
    
	sum=sum+ number;
    number++;
} //经过修改之后,循环就能正常运行

2.2.3 Application of commas in for statement

At Expression 1 and Expression 3 in the for statement, in addition to simple expressions, you can also use comma expressions. That is, it contains more than one simple expression, separated by commas. For example, to set initial values ​​for variables iCount and iSum at Expression 1, the code is as follows:

for(iSum=0,iCount=1; iCount<100; iCount++)
{
    
    
	iSum = iSum + iCount;
}

Or perform the loop variable self-increment operation twice, the code is as follows:

for(iCount=1;iCount<100;iCount++,iCount++)
{
    
    
	iSum=iSum+iCount;
}

Expression 1 and Expression 3 are both comma expressions. Within the comma expression, they are evaluated from left to right. The value of the entire comma expression is the value of the rightmost expression. For example:

for(iCount=1;iCount<100;iCount++,iCount++)
//就相当于:
for(iCount=1;iCount<100;iCount+=2)

2.3 Detailed explanation of break and continue usage in C language (jump out of loop)

When using a while or for loop, if you want to end the loop early (end the loop if the end condition is not met), you can use the break or continue keywords.

2.3.1 break keyword

When the break keyword is used in while and for loops, the loop will be terminated and the code following the entire loop statement will be executed. The break keyword is usually used together with the if statement to break out of the loop when the condition is met. Use a while loop to calculate the value of 1 added to 100:

#include <stdio.h>
int main(){
    
    
    int i=1, sum=0;
    while(1){
    
      //循环条件为死循环
        sum+=i;
        i++;
        if(i>100) break;
   }
    printf("%d\n", sum);
    return 0;
}

while loop condition is 1, which is an infinite loop. When the 100th loop is executed, the value of i after calculating i++; is 101. At this time, the condition i> 100 of the if statement is established, and the break; statement is executed. , end the cycle. In a multi-level loop, a break statement only jumps one level outward. For example, output an integer matrix 4*4:

/*================================================================
*   Copyright (C) 2023 AmoXiang All rights reserved.
*   
*   文件名称:10-break.c
*   创 建 者:AmoXiang
*   创建日期:2023年10月16日 17:37:06
*   描    述:
*
================================================================*/

#include <stdio.h>
int main(){
    
    
    int i=1, j;
    while(1){
    
      // 外层循环
        j=1;
        while(1){
    
      // 内层循环
            printf("%-4d", i*j);
            j++;
            if(j>4) break;  //跳出内层循环
        }
        printf("\n");
        i++;
        if(i>4) break;  // 跳出外层循环
    }
    return 0;
}

The program running result is as shown below:
Insert image description here
When j>4 is established, executebreak; and jump out of the inner loop; the outer loop is still executed , until i>4 is established, and jump out of the outer loop. The inner loop is executed a total of 4 times, and the outer loop is executed once.

2.3.2 continue statement

The function of the continue statement is to skip the remaining statements in the loop body and force entry into the next loop. The continue statement is only used in while and for loops, and is often used together with the if conditional statement to determine whether the condition is true. Let’s look at an example:

/*================================================================
*   Copyright (C) 2023 AmoXiang All rights reserved.
*   
*   文件名称:11-continue.c
*   创 建 者:AmoXiang
*   创建日期:2023年10月16日 17:41:13
*   描    述:
*
================================================================*/


#include <stdio.h>
int main(){
    
    
    char c = 0;
    while(c!='\n'){
    
      //回车键结束循环
        c=getchar();
        if(c=='4' || c=='5'){
    
      //按下的是数字键4或5
            continue;  //跳过当次循环,进入下次循环
        }
        putchar(c);
    }
    return 0;
}

The program running result is as shown below:
Insert image description here
When the program encounters while, the value of variable c is '\0', The loop conditionc!='\n' is established and the first loop starts. getchar() causes the program to pause execution, wait for user input, and does not start reading characters until the user presses the Enter key.

In this example, we input 0123456789. When 4 or 5 is read, the condition of ifc=='4'||c=='5' is established, and the continue statement is executed to end the current loop and directly enter the next loop. , that is to say, putchar(c); will not be executed. When other numbers are read, the if condition does not hold, the continue statement will not be executed, and putchar(c); will output the read characters. Comparison between break and continue: break is used to end all loops, and the loop statements no longer have a chance to be executed; continue is used to end the current loop and jump directly to the next loop. If the loop condition is true, the loop will continue.

2.4 Detailed explanation of loop nesting in C language

In C language, if-else,while,do-while,for can be nested in each other. The so-called nesting (Nest), means that there is another statement inside a statement, for example, there is a for inside a for, a while inside a while, or a for There is while in it, and if-else in while, which are all allowed.

Example 1: for nested execution process.

#include <stdio.h>
int main()
{
    
    
    int i, j;
    for(i=1; i<=4; i++){
    
      //外层for循环
        for(j=1; j<=4; j++){
    
      //内层for循环
            printf("i=%d, j=%d\n", i, j);
        }
        printf("\n");
    }
    return 0;
}

This example is a simple nested for loop. The outer loop and the inner loop are executed interleavedly. Every time the outer for is executed once, the inner for is executed four times. In C language, code is executed sequentially and synchronously. The current code must be executed before the subsequent code can be executed. This means that each time the outer for loops, it must wait for the inner for loop to complete (that is, loop 4 times) before it can proceed to the next loop. Although i is a variable, for the inner for, its value is fixed each time it loops.

Example 2: Output a 4×4 integer matrix.

#include <stdio.h>
int main()
{
    
    
    int i, j;
    for(i=1; i<=4; i++){
    
      //外层for循环
        for(j=1; j<=4; j++){
    
      //内层for循环
            printf("%-4d", i*j);
        }
        printf("\n");
    }
    return 0;
}

When the outer for loops for the first time, i is 1, and the inner for will output the value of four times1*j, which is the first row of data; after the inner for loop ends Execute printf("\n"), to output the newline character; then execute the i++ statement of the outer for. At this point, the first loop of the outer for loop ends. When the outer for loops for the second time, i is 2, and the inner for should output the value of 2*j four times, which is the data of the second row; then execute printf("\n") With i++, the second loop of the outer for loop ends. The outer for loops for the third and fourth times and so on. As you can see, the inner for outputs one data each time it loops, while the outer for outputs one row of data each time it loops.

Example 3: Output the multiplication table.

#include <stdio.h>
int main(){
    
    
    int i, j;
    for(i=1; i<=9; i++){
    
      //外层for循环
        for(j=1; j<=i; j++){
    
      //内层for循环
            printf("%d*%d=%-2d  ", i, j, i*j);
        }
        printf("\n");
    }
    return 0;
}

Like Example 2, the inner for outputs one piece of data each time it loops, and the outer for outputs one row of data each time it loops. It should be noted that the end condition of the inner for is j<=i. Each time the outer for loop loops, the value of i will change, so each time the inner for loop starts, the end condition is different. details as follows:

当 i=1 时,内层 for 的结束条件为 j<=1,只能循环一次,输出第一行。
当 i=2 时,内层 for 的结束条件是 j<=2,循环两次,输出第二行。
当 i=3 时,内层 for 的结束条件是 j<=3,循环三次,输出第三行。
当 i=456... 时,以此类推。

2.5 Summary of C language selection structure and loop structure

There are three commonly used programming structures in C language (the same is true for other programming languages). They are:

  1. Sequential structure: The code is executed sequentially from front to back, without any 拐弯抹角, skipping any statement, all statements will be executed. .
  2. Selection structure: also called branch structure. The code will be divided into multiple parts, and the program will determine which part to execute based on specific conditions (the result of an expression).
  3. Loop structure: The program will re-execute the same code until the condition is no longer met, or a forced jump statement (break keyword) is encountered.

2.5.1 Select structure

The keywords involved in the selection structure (branch structure) include if,else,switch,case,break, and a conditional operator? : (This is the only ternary operator in C language). Among them, if...else is the most basic structure. switch...case and ? : are both evolved from if...else. They are all designed to make it easier for programmers to write. You can use just if, or pair it with if…else. Also be good at using switch…case and ? :, sometimes they look cleaner. if...else can be nested. In principle, there is no limit to the nesting level (depth), but too many nesting levels will mess up the code structure.

2.5.2 Loop structure

Commonly used loop structures in C language include while loop and for loop. They can both be used to deal with the same problem and can generally replace each other. In addition to while and for, there is also a goto statement in C language, which can also form a loop structure. However, because the goto statement can easily cause code confusion, maintenance and reading difficulties, it has been criticized and is not recommended, and the goto loop can be completely replaced by other loops, so many subsequent programming languages ​​have canceled the goto statement, and I will not discuss it here. Give an explanation.

Many domestic universities still teach goto statements, but only to complete the courses set in the textbook. Goto statements are rarely seen in actual development. For while and do-while loops, the body of the loop should include statements that bring the loop to an end. For while and do-while loops, initialization of loop variables should be done before the while and do-while statements, while for loops can initialize loop variables internally. The for loop is the most commonly used loop. It is powerful and can generally replace other loops. Finally, note the difference between the break and continue keywords when used in loop structures:

break is used to jump out of all loops, and the loop statement no longer has a chance to be executed;
continue is used to end this loop and jump directly to the next loop. If the loop condition is true, The cycle will continue.

In addition, the break keyword can also be used to jump out of switch...case statements. The so-called 跳出, means that once a break is encountered, any statement in the switch will no longer be executed, including statements in the current branch and statements in other branches; In other words, the execution of the entire switch is completed, and then the code behind the entire switch will be executed.

This concludes today’s study. The author declares here that the author writes articles only for learning and communication, so that more readers who learn C language can avoid detours and save time. It is not used for other purposes. If there is any infringement, Just contact the blogger to delete it. Thank you for reading this blog post. I hope this article can be a guide on your programming journey. Happy reading!


Insert image description here

    I never get tired of reading a good book a hundred times, and I will know myself after reading the lessons thoroughly. And if I want to be the most handsome guy in the room, I must persist in acquiring more knowledge through learning, use knowledge to change my destiny, use my blog to witness my growth, and use my actions to prove that I am working hard.
    If my blog is helpful to you, if you like my blog content, please 点赞, 评论, 收藏 me!
 Coding is not easy, and everyone’s support is what keeps me going. Don’t forget to like Three consecutive hits with one click! I heard that those who like it will not have bad luck and will be full of energy every day! If you really want to have sex for nothing, then I wish you a happy day every day, and you are welcome to visit my blog often. 关注

Guess you like

Origin blog.csdn.net/xw1680/article/details/134051881