当前位置:网站首页>[sequence structure, branch structure, loop structure, continue statement, break statement, return statement] (learning Note 6 -- C language process control)
[sequence structure, branch structure, loop structure, continue statement, break statement, return statement] (learning Note 6 -- C language process control)
2022-06-13 01:47:00 【It's Beichen bupiacra】
C Language process control
C In language, different programs are executed according to the program , It's divided into sequential structures 、 Branching structure 、 And circular structure . Here is a simple case to show C Linguistic 3 It's a process structure .
One 、 Sequential structure
Sequential structure is the simplest process structure , It executes each statement one by one in a top-down manner .
Divide two integers ( The result is required to retain two valid decimal places )
#include<stdio.h>
int main()
{
int a,b;
float quotient;
printf("Please enter two integer:\n");
scanf("%d%d",&a,&b);
quotient = (float)a / b;
printf("a / b = %.2f\n",quotient);
return 0;
}
When the program calculates the result , The type conversion operator is used , It is the int Type variable a The type of is converted to float type , The purpose of this is to get a small number with a decimal point . Because of the variable a Converted to float type , So the variable b It will also be automatically converted to float type , Naturally you will get one float Operation result of type . And assign the result to the variable quotient. Finally through printf Function to print information on the control window by retaining two significant decimal places .
The execution flow of this program is :
1. The standard library header file “stdio.h” Include .
2. Execute the main function .
3. Define two int Type variable a and b.
4. Definition float Type variable quotient.
5. Use printf Function to print a prompt message .
6. Use scanf Function to get user input , And save it to the variable a and b in .
7. Yes a and b Use the division operator to perform an operation , And assign the result to quotient.
8. Use printf Function to print the final result
9. Exit main function , The program is finished
It can be seen that , The whole program is executed sentence by sentence from top to bottom .
Two 、 Branching structure
C The branch structure of the language can control whether part of the process of the program is executed , Or select one of multiple execution paths to execute .
1.if sentence
Format :
if( expression )
sentence
The expression in parentheses is the judgment condition , When the value of the expression is true , Execute statement ; When the value of the expression is false , Do not execute statements .
Code :
#include<stdio.h>
int main()
{
int a,b;
float quotient;
printf("Please enter two integer:\n");
scanf("%d%d",&a,&b);
if(b)
{
quotient = (float)a / b;
printf("a / b = %.2f\n",quotient);
}
return 0;
}
Can pass if Statement to divide by 0 Check the condition of , Only the divisor is not 0 when , To divide .
if(b) And if(b!=0) It is also a judgment variable b Whether the value of is not equal to 0, While using if(b) It will make the code more concise . Their The effect is actually the same .
2.if…else sentence
Format :
if( expression )
sentence 1
else
sentence 2
if…else Statement and if Statement than , More else part , A process of choosing one from the other Implementation .
Code :
#include<stdio.h>
int main()
{
int a,b;
float quotient;
printf("Please enter two integer:\n");
scanf("%d%d",&a,&b);
if(b)
{
quotient = (float)a / b;
printf("a / b = %.2f\n",quotient);
}
else
{
printf("Data is error!\n");
}
return 0;
}
When the divisor is not 0 when , The program prints out the normal results , Divisor is 0 when , Print a message that clearly informs the user .
3.if…else Statement nesting
Through to if…else Nesting of statements , You can let the program implement the process execution except one of many .
Ask the user to enter a 0 To 100 The integer of , To show students' test scores , The program can evaluate the corresponding grade according to this score , share A,B,C,D Four levels , among 90 Points and above are excellent ( use A Express ),80 To 89 Divided into good ( use B Express ),60 To 79 A pass ( use C Express ),60 Below is a failing grade ( use D Express ).
#include<stdio.h>
int main()
{
int score;
printf("Please enter a score between 0 and 100:\n");
scanf("%d",&score);
if(score >= 0 && score <= 100)
{
if(score>=90)
{
printf("A\n");
}
else
{
if(score>=80)
{
printf("B\n");
}
else
{
if(score>=60)
{
printf("C\n");
}
else
{
printf("D\n");
}
}
}
}
else
{
printf("Data is error!\n");
}
return 0;
}
4.if…else if…else sentence
Its execution process and utilization if…else The execution process of nested statements is the same , It can be considered that if…else if…else The sentence is right if…else A variant of statement nesting .
#include<stdio.h>
int main()
{
int score;
printf("Please enter a score between 0 and 100:\n");
scanf("%d",&score);
if(score >= 0 && score <= 100)
{
if(score>=90)
{
printf("A\n");
}
else if(score>=80)
{
printf("B\n");
}
else if(score>=60)
{
printf("C\n");
}
else
{
printf("D\n");
}
}
else
{
printf("Data is error!\n");
}
return 0;
}
5.switch…case sentence
It can also achieve the effect of selecting one from many , And make the logic of the code clearer .
#include<stdio.h>
int main()
{
int score;
printf("Please enter a score between 0 and 100:\n");
scanf("%d",&score);
if(score >= 0 && score <= 100)
{
switch(score / 10)
{
case 10:
case 9:
printf("A\n");
break;
case 8:
printf("B\n");
break;
case 7:
case 6:
printf("C\n");
break;
default:
printf("D\n");
break;
}
}
else
{
printf("Data is error!\n");
}
return 0;
}
break Statement can terminate switch…case Statement statement execution , If something is missing break, be switch…case Statement will not be terminated , The program will continue to execute the following statements , Until I met break Statement or represent the whole switch…case Closing brace at the end of the statement .
The integer expression is score/10, It's the original 0 To 100 The scores of , Conversion to 0 To 10 The scope of the .
default Labels can be placed anywhere , It can even appear in all case Before the label , therefore default Label under break Don't omit sentences at will .
3、 ... and 、 Loop structure
C The loop structure in language is to make the statement repeatable 、 A process structure that is executed many times .
1.while sentence
Format :
while( expression )
sentence
#include<stdio.h>
int main()
{
int i,n,score,sum = 0;
float aver;
printf("Please enter the number of students:\n");
scanf("%d",&n);
printf("Please enter the scores of %d students:\n",n);
i = n;
while(i--)
{
scanf("%d",&score);
sum += score;
}
aver = (float)sum / n;
printf("Total:%d , Average:%.2f\n",sum,aver);
return 0;
}
stay while The statement before , adopt i=n, Put variables n The value of is assigned to the variable i, Because we need to keep the number of students , It is also needed to calculate the average score later . namely while In the statement, we only operate and modify variables i, Not for variables n Have an impact on .
stay sum When defining a variable, you must initialize it , Let the variable sum The initial value of 0, If you don't do that , At the beginning sum The value of the variable is unknown , Even if students' grades are added up , The final calculated total score will not be correct .
2.do…while sentence
do…while Statement and while The sentences are similar ,do…while Is to execute the loop body first , Then check the value of the expression .
Format :
do
sentence
while( expression );
#include<stdio.h>
int main()
{
int i,n,score,sum = 0;
float aver;
printf("Please enter the number of students:\n");
scanf("%d",&n);
printf("Please enter the scores of %d students:\n",n);
i = n;
do
{
scanf("%d",&score);
sum += score;
}while(--i);
aver = (float)sum / n;
printf("Total:%d , Average:%.2f\n",sum,aver);
return 0;
}
3.for sentence
Format :
for( expression 1; expression 2; expression 3);
sentence
expression 1 Loop variables are usually initialized or assigned here ( Execute once during initialization )
expression 2 The loop body is executed when the value of the expression is true , End when false for sentence ( Before the loop body is executed )
expression 3 Loop variables are usually modified here 、 update operation ( After the loop body is executed )
If the expression 2 Omitted , The condition is always true , So it becomes an infinite loop , Lead to for Statement cannot end , We usually call this infinite loop an infinite loop .
#include<stdio.h>
int main()
{
int i,n,score,sum = 0;
float aver;
printf("Please enter the number of students:\n");
scanf("%d",&n);
printf("Please enter the scores of %d students:\n",n);
for(i = 0;i < n; ++i)
{
scanf("%d",&score);
sum += score;
}
aver = (float)sum / n;
printf("Total:%d , Average:%.2f\n",sum,aver);
return 0;
}
4. Nested use of loops
#include<stdio.h>
int main()
{
int n;
printf("Please enter a data!\n");
scanf("%d",&n);
for(int i=1;i <= n; ++i)
{
if(i % 2)
continue;
printf("%d ",i);
}
return 0;
}
Outer layer for Statement , Except for an inner layer for Out of statement , There is a printf Function call statements , It will be inside for Statement execution finished ( The inner loop body is executed 9 Time ) after , Perform a line feed operation .
Four 、 Flow control statement
1.continue sentence
characteristic :
1. Can only be used in statements with a loop structure
2. Usually and if Statement collocation
3. Once executed , The following statements will be skipped , Go straight to the next iteration
4. It only works on the loop that contains it
Format :
continue;
for(int i = 1; i <= 10; ++i)
{
if(i & 2)
continue;
printf("%d",i);
}
Print the results :
2 4 6 8 10
When variables i When the value of is odd , The value of the expression is true , This can lead to continue Statement executed . once continue Statement executed , Then the following printf Function call statements are no longer executed .
2.break sentence
A sharp weapon against the dead circle .
What to pay attention to :
1. Can only be used in switch…case Statement or loop structure
2. Usually with if Statements use
3. Once executed , Will force the process to be interrupted , End the execution of the statement
for(int i = 1; i <= 10; ++i)
{
if(i > 5)
break;
printf("%d",i);
}
result :
1 2 3 4 5
3.return sentence
return Statement can perform the function of forcibly stopping a function , That is, if there is in the function return Statement executed , Even if there are other statements , The execution process of the entire function will also end .
#include<stdio.h>
int main()
{
printf("AA\n");
return 0;
printf("BB\n");
}
result :
AA
return Statement must be used inside a function , Whether in sequential structure 、 Branching structure 、 Or a circular structure , Will cause the function execution process to be forced to end , If the main function is closed , It will lead to the end of the whole program .
边栏推荐
- Wildcard usage of go standard library FMT
- [andoid][step pit]cts 11_ Testbootclasspathandsystemserverclasspath at the beginning of R3_ Analysis of nonduplicateclasses fail
- Numpy multidimensional array transpose transpose
- Phaser3 load
- MySQL ---- where后使用字段别名
- Using atexit to realize automatic destruct of singleton mode
- STM32 3*3矩阵按键(寄存器版本)
- redis
- 移动IPv6光猫登录的一般ip地址账号与密码,移动光猫变桥接模式
- 水管工遊戲
猜你喜欢

dfs与bfs解决宝岛探险

What is the path field—— Competitive advertising

什么是立体角

Combining strings and numbers using ssstream

Opencv camera calibration (1): internal and external parameters, distortion coefficient calibration and 3D point to 2D image projection

关于tkinter.Canvas 不显示图片的问题

redis

Implementation and design of JMeter interface test database assertion for CSDN salary increase technology

Tweets movement description and chart display

What is Google plus large text ads? How to use it?
随机推荐
JSON and protobuf Any interchange
MySQL ---- where后使用字段别名
水管工遊戲
[pytorch FAQ] numpy:dll load failed while importing_ multiarray_ Umath: the specified module could not be found.
[wsl2]wsl2 migrate virtual disk file ext4 vhdx
Decompression and compression of chrome resource file Pak
Add default right-click menu
How do you use your own data to achieve your marketing goals?
DFS and BFS to solve Treasure Island exploration
Use koa to mock data and set cross domain issues
Detailed understanding of white noise
Phaser3 load
dfs与bfs解决宝岛探险
Plumber game
Machine learning basic SVM (support vector machine)
How does Google's audience work?
CXGRID keeps the original display position after refreshing the data
Auto commit attribute of MySQL
Getting started with phaser 3
Torch. Distributions. Normal