[C language] branch statement and loop statement

Table of contents

 1. What is a sentence?

 2. Branch statement

2.1 if statement

2.1.1 Floating else 

2.2 switch statement

 3. Loop statement

3.1 while loop

 3.1.1 break and continue in while loop

break

continue

3.2 for loop

【Exercise questions】

3.3 do...while() loop 

4. goto statement

5. Practice 


First of all, C language is a structured programming language, which is a language for communication between humans and computers.

The C language supports three structures:

  • sequential structure
  • select structure
  • loop structure

Sequential structure: Step 1->Step 2->Step 3... (step by step in order)

Selection structure: select based on criteria

 Loop structure: It is generally used in our recurring execution events.

 

 1. What is a sentence?

C language statements can be divided into:

  1. expression statement
  2. function call statement
  3. control statement
  4. compound statement
  5. empty statement

 Where branches and loops are control statements

C language control statements are:

  1. Branch statement (conditional judgment statement): if statement, switch statement
  2. Loop statement: do while statement, while statement, for statement
  3. Turn statement: break statement, goto statement, continue statement, return statement

 2. Branch statement

2.1 if statement

In C language, 0 means false, non-zero means true

//语法
if(表达式)  //表达式为真,就执行下面的语句
    语句;

if(表达式)    //表达式为真,就执行语句1
    语句1;
else          //表达式为假,执行语句2
    语句2;
#include<stdio.h>
int main()
{
    int age = 0;    //初始化变量
    scanf("%d",&age);
    if(age < 18)
    {
        printf("未成年");
    }
    else
    {
        printf("成年了!");    //age >= 18
    }
    return 0;
}

 Note: if statement is a kind of branch statement, which can realize single branch or multi-branch

//多分支
if(表达式1)
{
    语句1;
}
else if(表达式2)
{
    语句2;
}
else
{
    语句3;
}

Error-prone reminder:

#include<stdio.h>
int main() 
{
	int age = 0;
	scanf("%d",&age);
	if (age<18)
	{
		printf("少年");
	}
	else if(18<=age<30)    //注意此代码
	{
		printf("青年");
	}
	else if (age>=30&&age<50) 
	{
		printf("中年");
	}
	else 
	{
		printf("老年");
	}

}

else if(18<=age<30)

This statement is to judge 18<=age first and then judge age<30

If 18<=age is true (1), 1<30 is also true, the statement is executed

更正:else if(age>=18&&age<30)

 Simplify the code while keeping the order of the code state unchanged

#include<stdio.h>
int main() 
{
	int age = 0;
	scanf("%d",&age);
	if (age<18)
	{
		printf("少年");
	}
	else if(age<30)
	{
		printf("青年");
	}
	else if (age<50) 
	{
		printf("中年");
	}
	else 
	{
		printf("老年");
	}

}

2.1.1 Floating else 

else is matched with its closest if

#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;
}

If you don’t pay attention to it: it is printing haha, in fact, the real result is not printing anything

The correct code to print haha ​​is

#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

The switch statement is also a kind of branch statement, which is often used in multi-branch situations

 switch(expression)

{

        case integer constant expression:

                statement;

                break; //The actual effect is to divide the statement into different branch parts

        case integer constant expression:

                statement;

                break;         

        .....

        default:

                statement;

                break;

}

 Notice:

switch(expression)

The expression here can only be short, char, int, long integer, enumeration

Cannot be: float, double

After the case statement, the constant expression or enumeration type of the integer result is generally placed, and the enumeration type can also be regarded as a special constant

When the value of the expression does not match the value of the case, the statement of default is executed

The default clause in the switch statement can be placed anywhere, and the general case is best placed before default

#include<stdio.h>
int main()
{
	int n = 0;
	scanf("%d", &n);
	switch (n)
	{
	case 1:
		printf("吃饭\n");
	case 2:
		printf("睡觉\n");
	case 3:
		printf("打豆豆\n");
	default:
		printf("编程!!!");
	}
	return 0;
}

Note that there is no break here, when the keyboard enters 1

 join break

#include<stdio.h>
int main() 
{
	int n = 0;
	scanf("%d", &n);
	switch (n) 
	{
	case 1:
		printf("吃饭\n");
		break;
	case 2:
		printf("睡觉\n");
		break;
	case 3:
		printf("打豆豆\n");
		break;
	default:
		printf("编程!!!");
		break;
	}
	return 0;
}

 keyboard input 1

 Coherent use of case: when required

1. Input 1-5, the output is "weekday";
2. Input 6-7, the output is "weekend"

int main()
{
	int day = 0;
	switch (day)
	{
		case 1:
		case 2:
		case 3:
		case 4:
		case 5:
			printf("weekday\n");
		break;
		case 6:
		case 7:
			printf("weekend\n");
			break;
	}
	return 0;
}

 3. Loop statement

3.1 while loop

When an event we need to execute multiple times. While in C language, you can realize the loop

[Example] print numbers 1-10

#include <stdio.h>
int main()
{
 int i = 1;
 while(i<=10)
 {
 printf("%d ", i);
 i = i+1;
 }
 return 0;
}

 3.1.1 break and continue in while loop

break

Look at the output of the code below

#include <stdio.h>
int main()
{
	int i = 1;
	while (i <= 10)
	{
		if (i == 5)
			break;
		printf("%d ", i);
		i = i + 1;
	}
	return 0;
}

The resulting output is

 Summary: The function of break in the while loop directly terminates the loop, and the subsequent loop does not continue.

continue

Look at the output of the code below

#include <stdio.h>
int main()
{
	int i = 1;
	while (i <= 10)
	{
		if (i == 5)
			continue;
		printf("%d ", i);
		i = i + 1;
	}
	return 0;
}

 Output: 1 2 3 4 enters an infinite loop

[Example] Judging the output result

#include<stdio.h>
int main()
{
	int i = 1;
	while (i<=10)
	{
		i = i + 1;
		if (i==5)
			continue;
		printf("%d ",i);
	}
	return 0;
}

Error-prone, the output is easy to see: 2 3 4 6 7 8 9 10

But the result is: 2 3 4 6 7 8 9 10 11

Because i<=10 in the while loop, followed by i= i+1;

Summary: The function of continue in the while loop is to terminate this loop, that is, the code behind this loop will not be executed again, but will directly jump to the judgment part of the while statement to judge the entry of the next loop

3.2 for loop

for(expression1;expression2;expression3)

        statement;

  • Expression 1: Used to initialize the loop variable
  • Expression 2: Used to determine when the loop terminates
  • Expression 3: Adjustment for loop condition

 Example: use for loop to output 1-10

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

There can also be break and continue statements in the for loop

#include <stdio.h>
int main()
{
	int i = 0;
	for (i = 1; i <= 10; i++)
	{
		if (i == 5)
			break;
		printf("%d ", i);
	}
	return 0;
}

The result is: 1 2 3 4

Some variants of the for loop

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

The expression inside the for loop can sometimes be omitted. However, the omission of the judgment part will continue in a loop [not recommended to omit]

#include<stdio.h>
int main()
{
	int i = 0;
	int j = 0;
	for (i = 0;i<3;i++)
	{
		for (j = 0; j < 3;j++)
		{
			printf("6 ");//一共打印9个6
		}
	}
	return 0;
}

This is the nested loop

#include<stdio.h>
int main()
{
	int i = 0;
	int j = 0;
	for (;i<3;i++)
	{
		for (; j < 3;j++)
		{
			printf("6 ");//一共打印3个6
		}
	}
	return 0;
}

Result: 6 6 6

Because there is no initialization part in the two for loops, when the innermost loop j is equal to 3 (three 6s are printed), the condition is not satisfied when entering the loop later.

【Exercise questions】

//请问循环要循环多少次?
#include<stdio.h>
int main() 
{
	int i = 0;
	int j = 0;
	for (i = 0, j = 0; j = 0; i++, j++)
		j++;
	return 0;
}

 The result is: not looping once

Because the judgment part j = 0; that is, j is assigned a value of zero, which is false, and the loop cannot enter.

3.3 do...while() loop 

do

        loop statement;

while(expression);

The do...while() loop is executed once first, and then judged. If the expression is true, then execute the loop statement until the condition is not satisfied to stop.

4. goto statement

The most common place for the goto statement is to terminate the program in some deeply nested structure

Because in a multi-layer loop, jumping to a certain layer of loop, a break cannot be reached. The goto statement can do it. 

//goto语句运用
#include<stdio.h>
int main() 
{
	int i = 0;
	int error = 1;
	for (i = 0; i < 3;i++)
	{
		for (int j = 0; i < 3; i++) 
		{
			for (int k  = 0; k < 3; i++) 
			{
					goto end1;//跳转标记
			}
		}
	}
end1://所跳转的位置
	if (error)
	{
		printf("hh");
	}
	return 0;
}

Results of the:

 It is recommended to use goto statement as little as possible

5. Practice 

1. Calculate the factorial of n

//计算n的阶乘
#include <stdio.h>
int main() 
{
	int n = 0;
	int ret = 0;
	while (~scanf("%d",&n))//实现多组输入
	{
		int i = 0;
		ret = 1;
		for (i = 1; i <= n;i++)
		{
			ret *= i;
		}
		printf("%d\n",ret); 
	}
    return 0;	
}

2. Calculate the sum of factorials between 1-10

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

The output is:

Guess you like

Origin blog.csdn.net/qq_72505850/article/details/131766555