当前位置:网站首页>C language - Introduction - Foundation - grammar - process control (VII)
C language - Introduction - Foundation - grammar - process control (VII)
2022-07-04 19:47:00 【Hu Anmin】
The basic concept of process control
By default, after the program runs , The system will execute each line of code in the program from top to bottom in writing order . But this is not
Meet all our development needs , In order to facilitate us to control the running process of the program ,C Language provides 3 A process control structure , Different process control structures can realize different operation processes . this 3 The two process structures are Sequential structure 、 Selection structure 、 Loop structure
Basically, if computers can work like people, then process control is the core , No process control , There is no such thing as all current software , Simply put, the switch of your electric light is controlled by the process
Sequential structure
Execute from top to bottom according to the writing order of the code , That's not enough , All fools know
Selection structure
Judge the given condition , Then decide the execution code according to the judgment result
C The language provides two choice structures , Namely if and switch
Selection structure if
if
If the expression is true , Execute statement block 1, Otherwise, do not execute
#include <stdio.h>
int main() {
int age=25;
if (age >= 18) {
// true
printf(" Open the network card \n"); // perform
}
printf(" Buy cigarettes \n");
return 0;
}
if else
If the expression is true , Then execute the statement block 1, Otherwise, execute the statement block 2 ,else Can't get away from if Use alone
#include <stdio.h>
int main() {
int age=11;
if (age > 18) {
//false
printf(" Open the network card \n");
} else {
printf(" Call parents to drive \n"); // perform
}
printf(" Buy cigarettes \n");
return 0;
}
if else if
- If " expression 1" It's true , execute " Sentence block 1", Otherwise, judgment " expression 2", If it's true , perform " Sentence block 2", Otherwise, judge again " expression 3", If it's true , perform " Sentence block 3", When the expression 1、2、3 Are not satisfied , Will execute the last else sentence
- In many braces , Only the contents in one brace will be executed
- Only all the previous additions are not satisfied , Will execute else What's in braces
#include <stdio.h>
int main() {
int age=11;
if(age>40){
// false
printf(" Give me your room card ");
}else if(age>25){
printf(" Give me your business card ");
}else if(age>18){
printf(" To network card ");
}else{
printf(" Give the good man a card "); // perform
}
printf(" Buy cigarettes \n");
return 0;
}
if nesting
if You can continue to nest if, else You can also continue to nest if
if Be careful
Any value is true or false
When if else When there is only one statement after , if else The following braces can be omitted ( Not recommended )
When if else When the following braces are omitted , else Will automatically contact the nearest one if matching
If if else The braces are omitted , Then you can't define variables later
Selection structure switch
because if else if It's not simple enough , therefore switch And that's what happened , He followed if else if Complement each other .switch Provides point-to-point judgment , It is more efficient than if Just look at the matching pattern in the figure below quickly
You can see from the picture above ,if It takes a layer of judgment , and switch It only needs one judgment to directly locate the target , So in , A large number of single condition scenarios that need to be judged are multi-purpose switch however switch Can't replace if, because switch The judgment condition is relatively simple
Calculation " expression " Value , One by one " Constant expression " Value is compared with , When " expression " The value of is related to a " Constant expression " When the values of are equal , That is, execute the following statements , Then jump out switch sentence If " expression " The value of is the same as all case After " Constant expression " Are not the same , execute default The following sentence
Example
Be careful :
- switch Condition expression must be of type integer , Or it can be promoted to an integer value (char、short) , Otherwise, the editor reports an error
- case The value of can only be a constant , And it must also be an integer , Or it can be promoted to an integer value (char、short)
- case The values of the following constant expressions cannot be the same
- case Then you want to define variables , Must give case Add braces
case 1:{ Code }
- switch As long as any one of them case matching , All the others case and default It's going to fail . So if case and default There is no break There will be penetration problems
- switch in default It can be omitted
- switch in default You don't have to write to the end , No matter where you put it, you'll wait for all case Will not be executed until they do not match ( Except for penetration problems )
if and Switch transformation
it seems if and switch Can achieve the same function , So when do we use... In enterprise development if, When to use
switch Well ?
- if else if Multiplex selection for range
- switch It is for point-to-point selection
For example, judge whether the data entered by the user is greater than 100
From above 2 You can see from the picture if and switch In what environment ( Compare size and range using if, Judgment is equal to using switch …)
Loop structure
C The language provides three loop structures , Namely while、dowhile and for Loop structure is a very important structure in program . Its characteristics are , When a given condition holds , Executing a program segment repeatedly , Until the conditions don't hold . The given condition is called " The loop condition ", A program segment that is executed repeatedly is called " The loop body "
If you don't understand through the above figure , such as : You get up to eat in the morning and then go to work , Dinner after work in the evening , sleep , It's like this again and again every day , This is the cycle , Then you might say I can take a vacation , Then this is the condition judgment in the cycle process , So this is the computer program , Loops are particularly important in computers , Some automated scripts and automated programs are ok , It can be executed automatically without human control , This is the main reason why computers improve human efficiency , If there is no cycle, all tasks need to be performed manually one by one
Loop structure while
Several conditions constituting the cyclic structure
- Cycle control conditions ( Main basis for cycle exit , To control when the loop exits )
- The loop body ( Code snippets that are executed repeatedly during the loop )
- A statement that can end a loop ( Increasing 、 Decline 、 really 、 Fake wait , It can make the cycle condition false and exit the cycle )
while Circular execution flow
- First of all, we will judge " Cycle control conditions " Is it true , If false, skip directly to the end of the loop statement
- If " Cycle control conditions " It's true , Perform a loop body , Then judge again " Cycle control conditions " Is it true , For real, continue
- Execution loop body , Jump out of loop for false
- Repeat the above operation , until " Cycle control conditions " Until it's false
#include <stdio.h>
int main() {
int count = 0;
while (count < 3) {
printf(" bullets ~ Beep, beep, beep \n");
count++;
}
printf(" Loop execution complete \n");
return 0;
}
- Judge whether the cycle control condition is true , here 0 < 3 It's true
- Execute the code in the loop body , Print " bullets "
- perform " A statement that can end a loop " count = 1
- Judge whether the cycle control condition is true again , here 1 < 3 It's true
- Execute the code in the loop body , Print " bullets "
- perform " A statement that can end a loop " count = 2
- Judge whether the cycle control condition is true again , here 2 < 3 It's true
- Execute the code in the loop body , Print " bullets "
- perform " A statement that can end a loop " count = 3
- Judge whether the cycle control condition is true again , here 3 < 3 For false , Skip loop statements
- Execute the code after the loop statement , Print " Loop execution complete "
while Cycling considerations :
- Any value is true or false 0(false),1(true) , If the condition is always true, Then there will be an endless cycle ( Use... Depending on the situation )
- When while When there is only one statement after ,while The following braces can be omitted ( Not recommended )
- If while The braces are omitted , Then you can't define variables later ( Not recommended )
- The simplest dead cycle
while (1);
( Not recommended )
Loop structure do while
do while
and while
In fact, it's almost , That is, the condition is judged after the execution of the loop body , That is, the worst loop body will also be executed once
Example
do-while Circular execution flow
- In the first place while Whether the conditions in are true , It will be executed once " The loop body "
- After executing a loop body , Then judge again while Is the condition in true , If true, continue to execute the loop body , Jump out of loop for false
- Repeat the above operation , until " Cycle control conditions " Until it's false
Application scenarios ( Do it first , And then in the validation )
while and do…while Application scenarios
- In most cases while and dowhile interchangeable , So it works while Just use while
- In any case, you need to execute the loop body first , Only use do…while
do...while
Once proposed to abolish , But it's useful for input checking
Loop structure for
#include <stdio.h>
int main() {
for (int i = 0; i < 10; i++) {
printf(" bullets ~ Beep, beep, beep \n");
}
return 0;
}
for Circular execution flow
- First, execute " Initialization expression ", And throughout the cycle , The initialization expression will be executed only once
- Then judge " Loop condition expression " Is it true , Execute the statement in the loop body for true
- After the loop body is executed , And then it will execute " Operation expression after loop ", Then judge whether the condition is true again , It's true
- Continue to execute the loop body , Jump out of loop for false
- Repeat the process , Until the conditions are not established for loop
for Cycle considerations and while almost
- while What can be done for Can do it , So it can be used in development for Just use for, because for More flexible , And contrast while Come on for Save more memory space
- If the value of the initialization expression , Need to be used after the cycle , Then use while , If the value of the initialization expression , You don't need to use... After the loop , Then use for
- stay for Loop initializes the variables defined in the expression , Only in for After the loop {} Medium visit
- The simplest dead cycle
for(;;);
Four big jumps
C The language provides four jump statements , Namely return、break、continue、goto ,break:
break
End current operation , Applicable only switch And circular structure
break matters needing attention :
- break Leave the scope of application (for , switch), Existence is meaningless
- In a multi-level cycle , One break The statement just jumps out one level
- break There can be no statements below , Because it can't be implemented
continue
End the cycle , Enter the next cycle , Only applicable to circular structure
goto
This is a topic that is not worth discussing ,goto It destroys the structured programming process , It will make the program level unclear , And it is not easy to read. , So be careful , goto sentence , Jump can only be implemented in this function , Can't jump across functions . But he is very efficient when jumping out of multiple cycles
return
End current function , Return the result to the caller , The return type of the premise function is not void , There can be more than one in the same function return, But in the end, only those that meet the conditions will be returned , If all conditions are met , Then only the first one will be returned
grammar : return expression | value
More specific details need to be used when learning functions , Here you can know first
Nesting of loops
There are other cyclic structures in the cyclic body of the cyclic structure , We call it loop nesting , Generally speaking, one cycle solves linear problems , The double cycle and triple cycle can solve the plane and three-dimensional problems
Be careful :
- Generally, the nesting of loops should not exceed three layers , Otherwise, it's hard to maintain , Disaster.
- The number of times the outer loop is executed * The number of times the inner loop is executed is the total number of times the inner loop is executed
- In multiple loops , If possible , The longest loop should be placed on the innermost layer , The shortest cycle is on the outermost layer , In order to reduce CPU The number of times that the cyclic layer is cut across
边栏推荐
- QT realizes interface sliding switching effect
- Basic use of kotlin
- 1006 Sign In and Sign Out(25 分)(PAT甲级)
- Is it safe to open an account at Great Wall Securities? How to open an account when buying stocks
- BCG 使用之CBCGPProgressDlgCtrl进度条使用
- Abc229 summary (connected component count of the longest continuous character graph in the interval)
- Kotlin condition control
- 牛客小白月赛7 F题
- 1011 World Cup betting (20 points) (pat a)
- 1005 spell it right (20 points) (pat a)
猜你喜欢
CANN算子:利用迭代器高效实现Tensor数据切割分块处理
勾股数规律(任意三个数能够满足勾股定理需要满足的条件)
西门子HMI下载时提示缺少面板映像解决方案
多表操作-外连接查询
What should we pay attention to when doing social media marketing? Here is the success secret of shopline sellers!
上线首月,这家露营地游客好评率高达99.9%!他是怎么做到的?
Oracle with as ora-00903: invalid table name multi report error
FPGA timing constraint sharing 01_ Brief description of the four steps
92. (cesium chapter) cesium building layering
English语法_名词 - 使用
随机推荐
Mysql database basic operation -ddl | dark horse programmer
应用实践 | 蜀海供应链基于 Apache Doris 的数据中台建设
需求开发思考
Educational codeforces round 22 E. Army Creation
Personal thoughts on Architecture Design (this article will be revised and updated continuously later)
BCG 使用之CBCGPProgressDlgCtrl進度條使用
黑马程序员-软件测试--09阶段2-linux和数据库-31-43修改文件权限字母发的说明,-查找链接修改文件,查找文件命令,链接文件,压缩解压方式,vi编辑器基本使用,
求2的n次方
There are multiple divs in the large div, which are displayed on the same line. After overflow, scroll bars are generated without line breaks
1003 Emergency(25 分)(PAT甲级)
HDU 6440 2018 Chinese college student program design network competition
Dark horse programmer - software testing - stage 07 2-linux and database -09-24-linux command learning steps, wildcards, absolute paths, relative paths, common commands for files and directories, file
Opencv functions and methods related to binary threshold processing are summarized for comparison and use
Educational Codeforces Round 22 E. Army Creation
Niuke Xiaobai month race 7 F question
有关架构设计的个人思考(本文后续不断修改更新)
华为nova 10系列支持应用安全检测功能 筑牢手机安全防火墙
1006 sign in and sign out (25 points) (PAT class a)
Explore the contour drawing function drawcontours() of OpenCV in detail with practical examples
一文掌握数仓中auto analyze的使用