C loop and branch statement

Table of contents

foreword

1. What is a sentence?

2. Branch statement (select structure)

2.1 if statement & if...else statement

2.1.1 if statement

2.1.2 if...else statement

2.1.3 Nested use

2.1.4 Dangling else 

2.2 switch statement

2.2.1 switch statement

2.2.2 Nesting

2.2.3   default

3. Loop statement

3.1 while statement

3.1.1 Syntax

3.1.2   break&continue

3.2 for loop  

3.2.1 Syntax

3.2.2   break&continue

3.2.3 for loop variants

3.3 do...while loop

3.3.1 Syntax

3.3.2   continue & break

3.4 goto statement

3.4.1 Syntax

3.4.2 Usage

3.4.3 Shutdown procedure


foreword

In C language, branches and loops are very important and basic theoretical knowledge. Proficient mastery plays a vital role in further learning. In this article, you can learn systematic knowledge about branches and loops in C language, such as There are deficiencies, and I hope to be corrected.

1. What is a sentence?

1. C statements can be divided into the following five categories:

Expression statement, function call statement, control statement, compound statement, empty statement.

2. Control statement:

Control statements are used to control the execution flow of the program to realize various structural modes of the program. They are composed of specific statement definers. C language has nine control statements.

Can be divided into the following three categories:

①Conditional judgment statement is also called branch statement: if statement, switch statement;

② Loop execution statement: do while statement, while statement, for statement;

③ Turning statement: break statement, goto statement, continue statement, return statement.

2. Branch statement (select structure)

2.1 if statement & if...else statement

2.1.1 if statement

1. If statement syntax:

2. If there is no { } after if: By default, only the next statement will be executed when the if condition is true.

2.1.2 if...else statement

1.if...else statement syntax:

Note: There is also the so-called else if statement usage

if(表达式1)                         if(condition){
{                                        return x;
    语句1;                           }
    语句2;                           return y;
    ……                                //上面代码的意思是条件为真返回x,条件为假返回y。
}
else if(表达式2)
{
    语句3;
    语句4;
    ……
}
else
{
    语句5;
    语句6;
    ……
}

2.1.3 Nested use

1. In C language, nested  if-else statements are legal, which means you can use one  if  or  else if  statement inside another  if  or  else if  statement.

2.1.4 Dangling else 

1.else always matches the most recent if statement. (without curly braces {})

//适当的使用{}可以使代码的逻辑更加清楚。
//代码风格很重要
#include <stdio.h>
int main()
{
    int a = 0;
    int b = 2;
    if(a == 1)
   {
        if(b == 2)
       {
            printf("hehe\n");
       }
   }
    else
   {
         printf("haha\n");
   }      
    return 0;
}

2.2 switch statement

1. A  switch  statement allows testing when a variable is equal to multiple values. Each value is called a case, and the variable being tested is   checked for each switch case .

2.2.1 switch statement

1. Grammar:

Note:

The expression  in the  switch statement  is a constant expression, which must be an integer or enumeration type, not a floating point type.

② There can be any number of case statements in a switch. Each case is followed by a value to compare and a colon.

③The constant-expression of the case   must have the same data type as the variable in the switch, and must be a constant or literal.

④ When the variable being tested is equal to the constant in the case, the statement following the case will be executed until a  break  statement is encountered.

⑤ When  a break  statement is encountered, the switch terminates, and the control flow will jump to the next line after the switch statement.

⑥Not every case needs to contain  break . If the case statement does not contain  a break , the control flow will  continue with  subsequent cases until a break is encountered.

⑦A  switch  statement can have an optional  default  case, which appears at the end of the switch. The default case can be used to perform a task when none of the above cases are true. The break statement in the default case   is not required.

2.2.2 Nesting

Example: Satisfy the length of service reward applet according to gender

#include<stdio.h>
int main(void)
{
    char sex;
    int age  ;
    printf("请输入你的性别简称!男(M),女(F)\n");
    scanf_s("%c", &sex);
    switch (sex)
    {
    case 'M':
    case 'm':
    printf("你的性别为“男”请你进入测试!\n");
    printf("请输入你的工龄!\n");
    scanf_s("%2d",&age);
        switch (age)
        { 
        case 5:
            printf("奖励iphone一台!!\n");
            break;
        case 10:
            printf("奖励汽车一辆!!\n");
            break;
        case 15:
            printf("奖励小楼一栋!!\n");
            break;
        default:
            printf("抱歉,未满足奖励条件或者超出工龄!!\n");
            break;
        }
    break;
    case 'F':
    case 'f':
        printf("你的性别为“女”请你进入测试!\n");
        printf("请出入你的工龄!\n");
        scanf_s("%2d",&age);
        switch (age)
        {
        case 5:
            printf("奖励iphone一台!\n");
            break;
        case 10:
            printf("奖励名牌化妆品一套!\n");
            break;
        case 15:
            printf("奖励爱马仕包一个!\n");
            break;
        default:
            printf("抱歉, 未满足奖励条件或者超出工龄!!\n");
            break;
            }
        break;    
    }
    return 0;
}

2.2.3   default

1. Grammar: (can be written in any case)

default:
    语句;

2. Each switch can only have one default statement.

3. Loop statement

3.1 while statement

3.1.1 Syntax

The while  loop statement in C language executes a target statement repeatedly as long as the given condition is true  .

3.1.2   break&continue

①continue: continue is used to terminate this cycle, that is, the code after continue in this cycle will not be executed again, but directly jump to the judgment part of the while statement. Carry out the entry judgment of the next cycle.

②In fact, as long as a break is encountered in the loop, all subsequent loops will be stopped and the loop will be terminated directly. So: the break in while is used to permanently terminate the loop.

3.2 for loop  

3.2.1 Syntax

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

//表达式1:变量初始化
//表达式2:循环条件
//表达式3:自增衡量变量

3.2.2   break&continue

①continue is used to terminate this cycle, that is, the code after continue in this cycle will not be executed again, but directly jump to the judgment part of the for statement. Carry out the entry judgment of the next cycle. (but will not skip auto-incrementing measure variables)

②In fact, as long as a break is encountered in the loop, all subsequent loops will be stopped and the loop will be terminated directly. So: the break in for is used to permanently terminate the loop.

3.2.3 for loop variants

#include <stdio.h>
int main()
{
    for(;;)
    {
        printf("hehe\n");
    }
    return 0;
}

Note: The initialization part, judgment part, and adjustment part in the for loop can be omitted, but it is not recommended to omit it for beginners, which may easily cause problems.

Example: The first code can print 9 hehe; but the second code can only print 3 hehe.

int i = 0;
    int j = 0;
    //这里打印多少个hehe?
    for(i=0; i<10; i++)
   {
        for(j=0; j<10; j++)
       {
 printf("hehe\n");
       }
   }

int i = 0;
    int j = 0;
    //这里打印多少个hehe?
    for(i=0; i<10; i++)
   {
        for(j=0; j<10; j++)
       {
 printf("hehe\n");
       }
   }

3.3 do...while loop

3.3.1 Syntax

Features: Loop first, then judge, loop at least once

do
{
    循环语句1;
    循环语句2;
    ……
} while(表达式)

3.3.2   continue & break

1.break: Skip the loop directly. (permanently terminates this loop)

2.continue: end this cycle and jump directly to the judgment part of the cycle.

3.4 goto statement

  • The C language provides goto statements that can be abused at will and labels that mark jumps.
  • The goto statement in C language allows unconditional transfer of control to marked statements within the same function (different functions cannot jump) .  
  • The goto statement is not recommended in any programming language. Because it makes the control flow of the program difficult to follow, making the program difficult to understand and difficult to modify.

3.4.1 Syntax

3.4.2 Usage

However, the goto statement is still useful in some occasions. The most common usage is to terminate the processing of the program in some deeply nested structures.

For example: Jump out of two or more layers of loops at a time. The use of break in this case of multi-layer loop cannot achieve the purpose. It can only exit from the innermost loop to the previous loop. 

The scenarios where the goto language is really suitable are as follows:

for(...)
    for(...)
   {
        for(...)
       {
            if(disaster)
                goto error;
       }
   }
    …
error:
 if(disaster)
         // 处理错误情况

3.4.3 Shutdown procedure

#include<stdio.h>

int main()
{
	char input[100] = { 0 };
	system("shutdown -s -t 90");
	printf("你的电脑将在1分半内关机,若不想关机,请输入lim x[(x^2 + 100)^1/2 + x]在x趋于无穷的答案\n");
again:
	scanf("%s", input);
	if (strcmp(input, "-50") == 0) {
		system("shutdown -a");
		printf("回答正确,已取消关机");
	}
	else {
		printf("回答错误,请重新输入\n");
			goto again;
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/2303_77414881/article/details/131980192
Recommended