当前位置:网站首页>[C language foundation] 04 judgment and circulation
[C language foundation] 04 judgment and circulation
2022-07-06 10:44:00 【One reed to sail FP】
One 、 Judge
1、if sentence
// form 1: Single execution statement
if ( Judging expressions ) //")" No semicolon after
Execute statement
// form 2: Multiple execution statements ( Compound statement )
if( Judging expressions ) {
Execute statement 1
Execute statement 2
...
} //"}" There must be no semicolon after
- Calculate the relationship between two values , Called relational operators . The following table shows the common relational operators
2、 Relational operator
Operator | significance |
---|---|
== | equal |
!= | It's not equal |
> | Greater than |
>= | Greater than or equal to |
< | Less than |
<= | Less than or equal to |
- There are only two results of relational operation : Integers 1( The result is true ) And integer 0( The result is false ).
- All relational operators have a lower priority than arithmetic operators , But higher than the assignment operator . To determine whether they are equal == and != The priority of is lower than others , Continuous relational operations operate from left to right .
3、if - else sentence
// form 1: Single execution statement
if ( Judging expressions ) Execute statement else Execute statement
// form 2: Multiple execution statements ( Compound statement )
if ( Judging expressions ) {
Execute statement 1
Execute statement 2
...
}
else {
Execute statement 1
Execute statement 2
...
}
4、if Nesting of statements
if ( Judging expressions 1) {
Execute statement
} if ( Judging expressions 2) {
Execute statement
}
else {
Execute statement
}
else
And the nearest oneif
matching ;- Indent format cannot be in time
else
The match of ;
Suggest :
- stay
if
andelse
Always add{}
, Even if there is only one execution statement . - A match
if
andelse
Position alignment .
5、if Cascade of statements
if ( Judging expressions 1)
Execute statement
else if ( Judging expressions 2)
Execute statement
...
else if ( Judging expressions )
Execute statement
else
Execute statement
6、if Common errors in statements
1、 When executing a compound statement , Forget the parentheses
{}
.
- countermeasures : Always in
if
andelse
I'll put curly braces after it .
2、
if
Add a semicolon after . namely :if ( Judging expressions ); sentence // The upper and lower codes are equivalent if ( Judging expressions ) ; sentence
3、 Misuse
==
and=
if
Only required()
The value in is zero ( To judge as false ) Or nonzero ( Judge as true )
4、 Code style.
- stay
if
andelse
Then you must add braces{}
Form statement blocks ;- In braces
{}
The statement inside is indented by tab The location of .
7、 Multiple branches switch-case
Format :
switch ( Control expression ) {
// Control expressions can only be integer values
case Constant expression : sentence // Here " Constant expression " It can be a constant , It can also be a constant calculation expression , for example "2" or "1+1" All possible
...
case Constant expression : sentence
default : sentence
}
give an example :
switch(type) {
case 1:
printf("type = 1");
break; // Jump out of judgment
case 2: //"type" Meet the corresponding value , Jump directly to the corresponding case Statement place , Instead of judging from the top to the bottom from the beginning .
printf("type = 2");
break; // Jump out of judgment
case 3:
printf("type = 3");
break; // Jump out of judgment
default: // Other situations
printf("type= Other values ");
}
Particular attention : case It only indicates the starting position of the program after judgment , It's just “ entrance ”, Instead of dividing the program into segments . If there is no break Then we will not continue to judge , No matter later case What is the value of the , The program is still executed sequentially . For example, the following procedure :
// This procedure ,type=1 and type=2 The output is the same , because case 1: There is no break. if case 2 There is no break, Will continue to execute case 3 The following statement . Until I met break or "}" end .
switch(type) {
case 1:
case 2:
sentence
break;
case 3:
sentence
break;
default:
sentence
}
Two 、 loop
1、while
loop
while
Sentence format :
while( Loop judgment expression ) {
Loop statement
}
while
Cycle flow chart :
- The circulatory body should have the opportunity to change the conditions of circulatory judgment , Otherwise, it will become an endless circle .
while
Cycle means , Keep repeating the sentences inside the loop .while
Determine whether to continue the loop before the loop is executed , So it's possible that the loop hasn't been executed .( Anddo-while
Different )- The condition is the condition for the cycle to continue .
2、do-while
loop
do-while
Circular format :
do {
Loop statement
} while( Return the loop condition ); // There must be a semicolon here ( You can think of braces {} Bring your own semicolon )
do-while
Cycle flow chart :
do-while
The cycle will enter the cycle at least once ( Andwhile
Different )
Tips:
- Note the start and end values of the loop ;
- To simulate running a large number of cycles , It can simulate fewer cycles , And then infer ;
- Remember to save the original value before calculating , It may be useful later .
- Decomposition of integers ( How to get the number on each bit of an integer ):
- Integers %10, Get single digits ;
- Integers /10, Get ten digits ;
- Yes 2 Result %10, Get hundreds of digits
- ... And so on .
- ** Find the inverse ordinal number
- :**
int x, digit; //digit Is the last digit scanf("%d",&x); // Read the original number do { digit = x%10; // Get the last digit printf("%d",digit); // Output the last digit //ret = ret*10 + digit; x /= 10; // Remove the last digit from the original number }while(x!=0);
3、for
loop
Format :
for ( expression 1; expression 2; expression 3) {
sentence
}
// expression 1—— initial ( turn ) Conditions
// expression 2—— The cycle continues ( Repeat the loop body ) Conditions
// expression 3—— The last step before the end of each cycle
above for sentence Equivalent to The following statement :
expression 1;
while( expression 2){
sentence
expression 3;
}
for
Cyclic 3 Expressions can omit one of them .
Tips:3 Seed circulation
- If there's a fixed number of times , use
for
loop ;- If necessary 1 Time , use
do-while
loop ;- In other cases
while
loop .
3、 ... and 、 Cycle control
1、 Cycle control
break
: Out of the loop
( Jump out of this cycle completely , Including the current round and the number of subsequent rounds )continue
: End the cycle ahead of time
( Skip the remaining statements , Go straight to the next round ).
Program examples :
// Program for judging prime numbers
int x,i;
scanf("%d", &x);
int isPrime = 1;
for(i=2;i<x;i++){
if(x%i == 0){
isPrime = 0;
break; // As long as existence can be 1 Divide by numbers other than itself , End cycle
}
}
if(isPrime == 1) printf(" Prime number ");
else printf(" Not primes ");
2、 Multiple cycles
(1) A nested loop
- In each cycle , The variables that control the loop should be different , Otherwise, an error will be reported .
Program examples :
// Program for judging prime numbers
int x;
for(x=1;x<=100;x++){
int i;
int isPrime = 1;
for(i=2;i<x;i++){
if(x%i == 0){
isPrime = 0;
break; // As long as existence can be 1 Divide by numbers other than itself , End cycle
}
}
if(isPrime == 1) printf("%d ",x);
}
(2) Jump out of nested loop
break
andcontinue
Can only operate on the layer where it is located , When loop nesting exists , The cycle of other layers where it is not located still needs to continue , Will not be skipped .- The most appropriate way to jump out of multiple nesting is
goto
sentence . In other cases, try not to use , Otherwise, the structure of the program will be destroyed , It leads to poor readability .
Method 1 : The relay break
Program examples :
// use 1 horn 、2 Angular sum 5 Horn money , Find a solution
int x;
int one; two; five;
int exit = 0; // Judge break Whether to relay variables
scanf("%d", &x);
for(one = 1;one<=x*10;one++){
for(two = 1;two<=x*10/2;two++){
for(five = 1;five<=x*10/5;five++){
printf("%d Yuan is equal to %d individual 1 horn +%d individual 2 horn +%d individual 5 horn ",x,one,two,five);
exit = 1; // If found, change the relay variable
break;
}
if(exit) break; // Judge whether to relay
}
if(exit) break; // Judge whether to relay
}
Method 2 :goto
sentence
The basic structure :
【 Label statement 】
identifier : sentence
// Pay attention to the colons
【goto sentence 】goto identifier ;
Program examples :
for(one = 1;one<=x*10;one++){
for(two = 1;two<=x*10/2;two++){
for(five = 1;five<=x*10/5;five++){
printf("%d Yuan is equal to %d individual 1 horn +%d individual 2 horn +%d individual 5 horn ",x,one,two,five);
goto out; //out For the label that jumps out
}
}
}
out: // Jump out of position , Pay attention to the end of the colon
3、 Recycling
(1) front n Sum of terms
Program examples :
// seek f(n) = 1-1/2+1/3-1/4+...+1/n
int i,n;
int sign = 1; // Replace the sign
double sum=0.;
scanf("%d",&n);
for(i=1;i<=n;i++){
sum += sign*1./i;
sign = -sign; // Alternate polarity
}
printf("f(%d) = %f\n",n,sum);
(2) Integer decomposition
// Integer decomposition : For example, the input 10340, Output 1 0 3 4 0
int x;
scanf("%d",&x);
int mask = 1; //mask Storage 10 Multiple
int t = x;
// For different digits x, Find the same number of digits mask. For example, the input 100342,mask=100000
while(t>9){
t /= 10;
mask *= 10;
}
printf("x=%d, mask = %d", x, mask);
do{
int d = x / mask;
printf("%d",d);
if(mask>9){
//mask The judgment condition of this statement , Instead of x
printf(" ");
}
x %= mask;
mask /= 10;
}while(mask>0); //mask The judgment condition of this cycle , Instead of x
(3) Find the greatest common divisor
- Enumeration :
int a,b,i;
for(i=1; i<a&&i<b; i++){
if(a%i==0 && b%i==0) ret = i;
}
printf("%d and %d The greatest common divisor of is %d", a,b,ret);
2. division
Ideas :
- If b be equal to 0, End of calculation ,a Is the greatest common divisor ;
- otherwise , Calculation a And b The remainder of , Give Way a be equal to b, and b Equal to the remainder ;
- Back to step one .
Demo code :
// Find the greatest common divisor by division
int a,b,ret;
scanf("%d %d",&a,&b);
while(b!=0){
ret = a%b;
a = b;
b = ret;
}
printf(" The greatest common divisor is %d",a);
边栏推荐
- Use JUnit unit test & transaction usage
- MySQL20-MySQL的数据目录
- ByteTrack: Multi-Object Tracking by Associating Every Detection Box 论文阅读笔记()
- MySQL24-索引的数据结构
- Technology | diverse substrate formats
- MySQL21-用户与权限管理
- Timestamp with implicit default value is deprecated error in MySQL 5.6
- Typescript入门教程(B站黑马程序员)
- [paper reading notes] - cryptographic analysis of short RSA secret exponents
- Windchill配置远程Oracle数据库连接
猜你喜欢
MySQL25-索引的创建与设计原则
Security design verification of API interface: ticket, signature, timestamp
[unity] simulate jelly effect (with collision) -- tutorial on using jellysprites plug-in
MySQL18-MySQL8其它新特性
MySQL19-Linux下MySQL的安装与使用
Const decorated member function problem
PyTorch RNN 实战案例_MNIST手写字体识别
Mysql26 use of performance analysis tools
Mysql21 user and permission management
[reading notes] rewards efficient and privacy preserving federated deep learning
随机推荐
API learning of OpenGL (2004) gl_ TEXTURE_ MIN_ FILTER GL_ TEXTURE_ MAG_ FILTER
Security design verification of API interface: ticket, signature, timestamp
MySQL32-锁
Transactions have four characteristics?
Good blog good material record link
实现以form-data参数发送post请求
Moteur de stockage mysql23
Mysql36 database backup and recovery
Pytoch LSTM implementation process (visual version)
C language string function summary
Unicode decodeerror: 'UTF-8' codec can't decode byte 0xd0 in position 0 successfully resolved
Anaconda3 installation CV2
IDEA 导入导出 settings 设置文件
C语言标准的发展
Super detailed steps for pushing wechat official account H5 messages
API learning of OpenGL (2005) gl_ MAX_ TEXTURE_ UNITS GL_ MAX_ TEXTURE_ IMAGE_ UNITS_ ARB
保姆级手把手教你用C语言写三子棋
[paper reading notes] - cryptographic analysis of short RSA secret exponents
MySQL transaction log
高并发系统的限流方案研究,其实限流实现也不复杂