当前位置:网站首页>C language branch and loop statements
C language branch and loop statements
2022-04-21 14:05:00 【Hair is not as much as code】
Catalog
Branch statement ( Selection structure )
if else if else give an example
continue stay for The role in the cycle
break stay for The role in the cycle
for Circulating lightning protection
continue stay do...while The role of
break stay do...while The role of
Branch statement ( Selection structure )
In life, we will encounter many selective problems , It looks like this

stay C In language , How to realize this choice ?
if sentence
Grammatical structure : The way 1: if( expression )
sentence ;
The way 2:
if( expression )
sentence 1;
else
sentence 2;
The way 3:
if( expression 1)
sentence 1;
else if( expression 2)
sentence 2;
else
sentence 3;
if Sentence example
int main()
{
int age = 0;
scanf("%d", &age);
if(age<18)
{
printf(" A minor \n");
}
}
Enter an age , If the age is less than 18 Print minor
if else Sentence example
#include <stdio.h>
int main()
{
int age = 0;
scanf("%d", &age);
if(age<18)
{
printf(" A minor \n");
}
else
{
printf(" adult \n");
}
}
Enter an age , If the age is less than 18 Print minors , If you are older than 18 Print adult
if else if else give an example
#include <stdio.h>
int main()
{
int age = 0;
scanf("%d", &age);
if(age<18)
{
printf(" juvenile \n");
}
else if(age>=18 && age<30)
{
printf(" youth \n");
}
else if(age>=30 && age<50)
{
printf(" middle-aged \n");
}
else if(age>=50 && age<80)
{
printf(" The elderly \n");
}
else
{
printf(" Old birthday star \n");
}
}
Enter the age , If age <18, Print juvenile
Age >=18 And age <30, Print youth
Age >=30 And age <50, Print middle age
Age >=50 And age <80, Print old
If the age is not in the above number field , Print old birthday
matters needing attention : If if or else or else if The following expression statement , More than one sentence , We need to use it. {} Will belong to if Or of else Or of else if Enclose the sentence
Judge the condition
stay C In language ,0 For false , Not 0 It's true , When selecting a statement () When the content is true , The expression of the current statement will be executed .
else and if Matching problems
#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;
}

We found nothing printed at this time , This is because ,a=0, Can't get into if(a==1) expression , here if(b==2) It belongs to if(a==1) The expression of , So you can't execute if(b==2), there else with if(b==2) A match , namely else That is closest to and within the same scope if Want to match
Correct input method
#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;
}
switch sentence
switch Statement is also a branch statement . It is often used in the case of multiple branches .
such as : from 1-7 For each number entered in the, the corresponding week will be printed . If used if The sentence is useful 7 Time , A little bit of a problem , At this point, we can use another statement called switch sentence
switch Sentence format ,switch( Integer expression )
{ case Integer constant expression : sentence ; }
from 1-7 Enter numbers in , Print the corresponding week
#include <stdio.h>
int main()
{
int day = 0;
switch(day)
{
case 1:
printf(" Monday \n");
break;
case 2:
printf(" Tuesday \n");
break;
case 3:
printf(" Wednesday \n");
break;
case 4:
printf(" Thursday \n");
break;
case 5:
printf(" Friday \n");
break;
case 6:
printf(" Saturday \n");
break;
case 7:
printf(" Sunday \n");
break;
}
return 0;
}
break The role of : If input 1, Print no after Monday break, The program will automatically go down , Get into case2 Until I met break Jump out of the program or until switch End of sentence .


But if the value entered exceeds case What about the scope after the statement ?C In language , When switch() The value in does not correspond to case When , We can use defalut sentence .
default Sentence function : When switch() The value entered in case When there is no corresponding condition in , That is, beyond case The scope of time , This statement will be unified into default sentence ,default stay switch Position in statement , It has no effect on the output results , But most people put it in by default switch{} At the end of .
matters needing attention :switch( Shaping expression ),() The content in can be an integer expression , It can also be char type , Because the character type itself is also plastic , This is because it is still ASCII Code value to save ,case Integer constant expression : sentence ; case The expression after must be a constant , It can't be a variable , If it is a variable, an error will be reported .
switch nesting
switch Statements allow nested use of

#include <stdio.h>
int main()
{
int n = 1;
int m = 2;
switch (n)
{
case 1:
m++;
case 2:
n++;
case 3:
switch (n)
{//switch Allow nesting
case 1:
n++;
case 2:
m++;
n++;
break;
}
case 4:
m++;
break;
default:
break;
}
printf("m = %d, n = %d\n", m, n);
return 0;
}
Loop statement
while() loop

while( expression )
Loop statement ;
Print... On the screen 1-10
#include <stdio.h>
int main()
{
int i = 1;
while(i<=10)
{
printf("%d ", i);
i = i+1;
}
return 0;
}

while( expression )
Loop statement ;
Use while When the sentence is , First, we will judge the expression , If the expression is true , Then execute the loop statement , If the expression is false , Do not enter while loop
break and continue
When we use in a loop break after


It was originally printed 1-10, But use break After that, only 1-4, This is because entering while After the cycle, there is a if(i==5), Here, judge i Is it 5, if 5 execute break sentence , When i==5 when , Yes break sentence , After that, no numbers were printed , This is because break The function of the statement is to jump out of the current loop
When we use in a loop continue after

The cursor is still flashing

When used here continue after , Print ;1-4, not used continue Print 5, This is because... Is not used continue when , There is a judgment condition (i==5) Judge i Is it equal to 5, If i be equal to 5, Just print , Use continue after , The program will automatically jump to while() Then move on , When you meet again continue after , Still jump to while Then move on , So at this time i Always equal to 5
for loop
for( expression 1; expression 2; expression 3)
Loop statement ;
expression 1 expression 1 For the initialization part , Used to initialize loop variables .
expression 2 expression 2 For the conditional judgment part , Used to determine when a loop ends .
expression 3 expression 3 For the adjustment part , For adjustment of cyclic conditions .
use for Loop printing 1-10
for Cycle flow chart

for The expression is executed at the beginning of the loop 1. And then we do the expression 2 Judge , If the second is true, execute the loop statement , Then execute expression three , Know the expression 2 Stop the cycle for false

continue stay for The role in the cycle

stay for Use in statement continue after , When the statement is executed continue after , The program will then execute the expression 3
break stay for The role in the cycle

stay for Use in statement continue after , When the statement is executed break after , The program will jump directly out for loop
for Cycle characteristics
for The loop can omit the expression 1,2,3, But when the expression 2 Omit , expression 2 The default condition is constant , As shown in the figure below, it will enter a dead cycle .

for Loops can also be in statements 1 Build variables , And assign a value to it , However, this method is generally not recommended for loop

for Circulating lightning protection

#include <stdio.h>
int main()
{
int i = 0;
int k = 0;
for (i = 0, k = 0; k = 0; i++, k++)
k++;
return 0;
}
This program will not enter for loop , Because of the expression 2 For an assignment statement instead of a judgment statement , take 0 Assign to k,k This is false , So the program will never enter for loop
do...while() loop
do
{
Loop statement ;
}while( expression );

do...while A loop is to execute the statements in the loop first , And then judge the conditions , If the condition is true , Then continue to execute the loop , Otherwise jump out of the loop

continue stay do...while The role of

When i be equal to 5 when , perform continue sentence , At this point, the program will always execute if(i==5) and continue, So the cursor is flashing all the time
break stay do...while The role of
here 4 The following cursor stops flashing , Explain that the program has been executed , When i==5 when , perform break, The program will jump directly out of the loop

goto sentence
C The language provides a language that can be abused at will goto Statement and mark the label of jump . In theory, goto Statements are not necessary , In practice, there is no goto Statements can also easily write code . But on some occasions goto Statements are still useful , The most common use is to terminate the processing of structures nested in some depth cheng . for example : Jump out of two or more loops at a time . Multilayer loops are used in this case break You can't achieve your goal . It can only exit from the innermost loop to the upper loop .
goto A statement is when a statement is executed , encounter goto After statement , Will automatically jump to goto Where indicated by the statement , The program then goes on , Now, yes goto Correct use of statements
for(...)
for(...)
{
for(...)
{
if(disaster)
goto error;
}
}
…
error:
if(disaster)
// Handling error situations
give an example
We found the command prompt in the computer , And enter the shutdown -s -t 60, It means that the computer starts after this statement is executed 60s Countdown shutdown , When you type... Again shutdown -a when , Will cancel the shutdown command

however goto Statements have certain limitations , We try to use less goto sentence , Replace... With other statements goto sentence ,stdlib.h yes system The header file ,strcmp The header file for is string.h
#include <stdio.h>
#include <stdlib.h>
int main()
{
char input[10] = {0};
system("shutdown -s -t 60");
while(1)
{
printf(" The computer will be in 1 Shut down in minutes , If input : I am a pig , Just cancel the shutdown !\n Please enter :>");
scanf("%s", input);
if(0 == strcmp(input, " I am a pig "))
{
system("shutdown -a");
break;
}
}
return 0;
}

版权声明
本文为[Hair is not as much as code]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204211352335998.html
边栏推荐
- Zabbix5 series - report tool zbxtable (XVIII)
- Redis master-slave replication and persistence
- Zabbix5 series - nail alarm (XV)
- 如何在机房限制学生端摆脱老师的控制,实现自由上网
- Shandong University project training raspberry pie promotion plan phase II (VI) condition judgment and cycle
- 用C语言实现有序数组的二分查找
- Zabbix5 series - monitoring Hikvision camera (VII)
- The importance of computing edge in Networkx: edge intermediate number or intermediate centrality edge_ betweenness
- SQL注入漏洞靶场-sqli-labs学习
- MySQL存储引擎
猜你喜欢

RHCE builds a simple web site

无穷小的比较

2021-08-16记一次无意发现正方教务系统的bug

微积分之微分

一篇文章带你初步了解c语言操作符基础知识

C语言选择和循环经典习题

Flow analysis (CTF)

Dual homing uplink - active / standby / load

The stack concept is transformed into cyclic bracket matching inverse Polish expression simulation to achieve full dry goods

Zabbix5系列-监控redis (十一)
随机推荐
MySQL storage engine
Numpy foundation of pytorch machine learning
Network port number and protocol number (Daquan)
如何在机房限制学生端摆脱老师的控制,实现自由上网
双归上行--主备/负载
Zabbix5系列-声音告警、邮件告警 (十四)
The importance of computing edge in Networkx: edge intermediate number or intermediate centrality edge_ betweenness
剑指office-割线子
电脑端微信内置浏览器开启调试模式
CEPH multi monitor for high availability
Redis master-slave replication and persistence
Tcpdump packet capture and nmap are easy to use
tcpdump抓包与nmap简单使用
MarkDown格式
洛必达法则
< 2021SC@SDUSC > Application and practice of software engineering in Shandong University jpress code analysis (8)
函数单调性与凹凸性
pipeline
Shandong University project training raspberry pie promotion plan phase II (I) project overview and introduction to raspberry pie
iscsi