当前位置:网站首页>4. Branch statements and loop statements
4. Branch statements and loop statements
2022-07-06 13:43:00 【It's Wang Jiujiu】
I learned before C In language , It's all sequential , Statements are executed in top-down order , There is no need to judge the cohesion between sentences , After executing the previous statement, automatically execute the next statement . But in practice , It depends on whether a certain condition is met , To decide whether to execute a program or choose to execute a program .C There are abundant control statements in the language , Control statements can be divided into three categories :
1. Conditional statements ( Branch statement ):if sentence 、switch sentence ;
2. Loop statement :while sentence 、for sentence 、do while sentence ;
3. Turn to statement :return sentence 、break sentence 、continue sentence 、goto sentence .
Catalog
if General structure of statements
switch The general format of the statement
while General structure of statements
while Statement break and continue
for General structure of statements
for Statement break and continue
do...while General structure of statements
do...while Statement break and continue
Branch statement
In reality, there are many situations that need to be judged and selected .
for example : Take the test , If we choose to study hard before the exam , You can get good grades ; If you choose not to study , You can only take the make-up exam ; If you choose to cheat , Will be expelled from school .
(1)if sentence
if General structure of statements
a. b. c.
if( expression ) if( expression ) if( expression 1)
sentence ; sentence ; sentence ;
else else if( expression 2)
sentence ; sentence ;
else
sentence ;
notes :
- Execute if expression is true , If it is false, it will not be executed .C In language 0 Express false , Not 0 Express really . therefore ,if(1) Must carry out ,if(0) Do not execute .
- If the statement is a multi segment statement , Then it needs to be enclosed in braces , The enclosed part is a code block .( In order to form good habits , It's best to enclose them in braces )
if Use of statements
Enter a student's math test score , Fail in judgment 、 pass 、 good 、 Or excellent .
#include<stdio.h>
int main()
{
int math = 0;
scanf("%d", &math);
if (math >= 0 && math < 60)//&& For logic and operators , When both sides of the operator are true, execute , If one is not true, it will not be executed
{
printf(" fail, \n");
}
else if (math >= 60 && math < 70)
{
printf(" pass \n");
}
else if (math >= 70 && math < 90)
{
printf(" good n");
}
else if (math >= 90 && math <= 100)
{
printf(" good \n");
}
else
printf(" Input error \n");
return 0;
}
notes :
- && For logic and operators , When both sides of the operator are true, execute , If one is not true, it will not be executed .
- (math >= 0 && math < 60) It can be understood as : A score greater than or equal to 0 branch also Less than 60 branch
- || Is a logical or operator , If one of the two sides of the operator is true, execute , If all are false, do not execute .
- (math < 60 || math > 90) It can be understood as : The score is less than 60 branch perhaps Greater than 90 branch
The total score of different rolls is different , The corresponding standards are also different , We can use what we have learned before #define Defined constants to represent , This can greatly reduce the amount of tasks when modifying code .
for example :
#include<stdio.h>
#define pass 60
#define good 70
#define good 90
#define Full marks 100
int main()
{
int math = 0;
scanf("%d", &math);
if (math >= 0 && math < pass )
{
printf(" fail, \n");
}
else if (math >= pass && math < good )
{
printf(" pass \n");
}
else if (math >= good && math < good )
{
printf(" good \n");
}
else if (math >= good && math <= Full marks )
{
printf(" good \n");
}
else
printf(" Input error \n");
return 0;
}
C Operators in language :
C The addition, subtraction and multiplication in language are consistent with our daily understanding 、 Except for slightly different . If it's two Integers be divided by , The result is divided by two numbers merchant .
for example :5/2=2 . Want decimal results , Just change one of the integers to Decimal structure that will do , for example :5.0/2=2.5 .
Besides ,C There is also... In the language modulus Operator %, Taking modulus is taking remainder , for example 5%2=1, This 1 Namely 5 Divide 2 The remainder of .
Judge whether a number is odd .
#include<stdio.h>
int main()
{
unsigned int num = 0;// Unsigned integer
scanf("%d", &num);
if (num % 2 == 1)
{
printf(" Is odd \n");
}
else
{
printf(" It's not an odd number \n");
}
return 0;
}
Because only positive integers have the concept of parity , also 0 It is also specified in even numbers . So we can set an unsigned integer to store variables num. Not odd in positive integers , It must be even , So when we finish judging odd numbers , There is no need to judge the even part .
notes :
- == To determine whether the equality operator ,(num % 2 == 1) It means : Judge num%2 The remainder of Is it equal to 1 .
- When if Only One When equal sign , It is no longer judgment , It is assignment 了 , quite a lot bug From this .
- for example :if(a=1) It means that 1 The value is assigned to a, because 1 Right and wrong 0, therefore if Conditions must be implemented .
Output 1 To 100 Between the odd numbers .
#include<stdio.h>
int main()
{
int num = 1;
while (num <= 100)
{
if (num % 2 == 1)
{
printf("%d ", num);
num++;// And num=num+1 Empathy
}
else
num++;
}
return 0;
}
because if Yes conditional statement , Print 1 To 100 The odd number between requires a loop , Here you can use while loop ,while The cycle will be discussed below .
notes :
- a++ For post ++, After ++ by : First use , Again ++; for example :b=a++ It means , First the a The value is assigned to b, then a Add 1.
- ++a For the front ++, In front of ++ by : First ++, Reuse ; for example :b=++a It means , First the a Add 1, then a The value is assigned to b.
- Whether it's ++a, still a++, In the end, it will be change a Value .
(2)switch sentence
switch The general format of the statement
switch( Integer expression ) // The return value of an expression must be an integer
{
case Integral constant expression : // for example case 1 case2 wait ...
sentence ;
break; //break After execution , There will be no further execution , Jump out of switch, To branch
default: //defalut Is the default , Only execute when a match cannot be found
sentence ;
}
notes :
- red The marked part is in general format , Is indispensable .
switch Use of statements
Enter a positive integer (1~7), To judge the day of the week , If the input is out of range , Prompt input error .
#include<stdio.h>
int main()
{
int input = 0;
scanf("%d", &input);
switch (input)
{
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;
default:
printf(" Input error \n");
}
return 0;
}
Suppose that each time break After deleting , What will happen? ?
If we enter 4, Then the compiler will start from case 4 Get into , And keep going . therefore break It's just switch The key to branch .
If the demand changes , Input 1~5 Show working days , Input 6~7 Show rest days , How to achieve ?
#include<stdio.h>
int main()
{
int input = 0;
scanf("%d", &input);
switch (input)
{
case 1:
case 2:
case 3:
case 4:
case 5:
printf(" Working day \n");
break;
case 6:
case 7:
printf(" Rest Day \n");
break;
default:
printf(" Input error \n");
}
return 0;
}
notes :
- One switch There can only be One default sentence ,default Statements can be placed in switch Statement whatever Location , But in general recommend take default Put the sentence in Last .
Loop statement
We introduced the sequence structure and branch structure , But these two structures are not enough , So we also need a circular structure ( Repeat structure ). Sequential structure 、 Selection structure 、 Loop structure is the three basic structures of structured programming , It is the basic unit of various complex programs .
(1)while sentence
In previous studies , It is used to judge whether a number is odd if sentence , however if Statement can only be executed once , Want to print 1-100 Between odd numbers , Yes while loop , We set a variable a, initialization a=1,while(a<=100), Every cycle will judge a Is it odd , also a++, When a>100 when , The cycle jumps out , This is a simple one while loop .
while General structure of statements
while( expression ) // If the expression is true, execute , If it is false, it will not be executed
{
Loop statement ; // Each loop should be close to the conditional value of the expression , Jump out of while, Otherwise, there will be an endless cycle
}
while Statement break and continue
break:while Medium break Will be terminated while All cycles of , Just meet break, Will jump out of the current while loop .
#include<stdio.h>
int main()
{
int i = 0;
while (i < 10)
{
i++;
if (i == 5)
{
break;
}
}
printf("%d\n", i);// The result is 5
return 0;
}
The test shows that i The value of is 5, although 5<10, But by break Out of the way while loop .
notes :
- If it is multi-layer loop nesting ,break Can only jump out of First floor loop , If you want to jump out of the multi-level cycle at once, you can use goto sentence , The back can speak goto Usage of sentences .
continue:while Medium continue Will terminate this cycle ,continue The latter part will not be executed , Jump straight to while The judgment part of a sentence .
#include<stdio.h>
int main()
{
int i = 0;
while (i < 10)
{
i++;
if (i == 5)
{
continue;
}
printf("%d ", i);
}
printf("\n");
return 0;
}
The test shows that , When i=5 when ,continue Skipped the following printing , Directly to the next cycle .
notes :
- continue Is to jump out of this cycle , A branch statement is not a loop statement , so switch Can't use continue.
(2)for sentence
for Statements are more flexible , Except when it can be used to determine the number of cycles , It is still applicable when the number of cycles is uncertain .
for General structure of statements
for( expression 1; expression 2; expression 3) // expression 1 by : Initialization part , Used to initialize loop variables .
{ // expression 2 by : Condition judgment part , Used to determine when a loop ends .
Loop statement ; // expression 3 by : Adjustment part , For adjustment of cyclic conditions .
}
for The execution process of the statement is : First, execute the expression 1( Throughout for In circulation , expression 1 Only once ), Then execute the expression 2, If the expression 2 If it is false, it will jump out of the loop , If the expression 2 If it is true, the loop statement , Then proceed to the expression 3. The next cycle is : expression 2—— Loop statement —— expression 3—— expression 2 The cycle of .
use for Loop printing on the screen 1~10 A digital
#include<stdio.h>
int main()
{
int i = 0;
for (i = 1; i <= 10; i++)
{
printf("%d ", i);
}
return 0;
}
i=1 For the initialization part , Because the printed numbers are from 1 Start , So will i Initialize to 1 that will do .
i<=10 For the judgment part , When i<=10 when , Execute loop statement ,i>10 Out of the loop .
i++ For the adjustment part , At the end of each cycle i++, Getting closer to the condition value of the decision part .
for Recycling is very convenient , It can completely replace while sentence .
for Statement break and continue
for Statements can also be inserted break and continue, And their usage is similar to while The usage in is consistent ,continue There is a slight difference in the use of .
break:
#include<stdio.h>
int main()
{
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", i);
if (i == 5)
{
break;
}
}
putchar('\n');
return 0;
}
When i=5 when ,if The expression is judged to be true , perform break Out of the loop , Final print 1 2 3 4 5.
continue:
#include<stdio.h>
int main()
{
int i = 0;
for (i = 0; i < 10; i++)
{
if (i == 5)
{
continue;
}
printf("%d ", i);
}
putchar('\n');
return 0;
}
here printf Function in continue Back , When i=5 when ,if The expression is judged to be true ,continue Execute to jump out of this cycle , Come to the adjustment section i++(while In the loop continue Is to jump directly to the judgment part ,for If the loop also jumps to the judgment part, it will lead to an dead loop , So we should jump to the adjustment part first , Then judge ).
for Skills in using sentences
(1)for The initialization part of the statement 、 Judgment part 、 The adjustment part can be omitted .
#include <stdio.h>
int main()
{
for (;;)
{
printf("hello ");
}
return 0;
}
Even if for In the loop 3 All parts are omitted , The code can still be executed , however 3 If all parts are omitted, the code will enter an endless loop , Unlimited printing “hello”.( It is not recommended to omit )
(2)for Nested use of loops
Print the multiplication table
#include<stdio.h>
int main()
{
int i = 0;
int j = 0;
for (i = 1; i < 10; i++)
{
for (j = 1; j <= i; j++)
{
printf("%d*%d=%2d ", j, i, j * i);//%2d Set the field width to 2, In this way, right alignment can be achieved
}
printf("\n");
}
return 0;
}
Set two variables i and j, Through two for Loop nesting to achieve the printing of multiplication formula table . Print one line at a time , Print a line break at the end of the first loop , Automatic line feed .
Because the product of two numbers has both single and double digits , So in order to keep the pithy table right , We set the number of the last product when printing %2d, That is, the domain width is 2 The integer of , So you can keep the right alignment , Make the pithy formula table more beautiful .
(3) Set up multiple variable control loops
#include<stdio.h>
int main()
{
int i=0, j=0;
for (i = 0, j = 0; i < 4 && j < 5; ++i, j+=2)
{
printf("hello\n");// Print 3 Time
}
return 0;
}
There are some slightly complicated situations , You can set multiple variables to help control the loop . The above code is printed three times hello, When the third loop statement ends ,++i,j+=2,i The value of is 3,j The value of is 6, The condition is judged as false , End of cycle .
How many times will the following code be executed ?
#include <stdio.h>
int main()
{
int i = 0;
int j = 0;
for (i = 0, j = 0; j = 0; i++, j++)
{
j++;
}
return 0;
}
answer :0 Time . Be careful : The condition judgment part is j=0, This is the assignment operation , take 0 The value is assigned to j, because 0 For false , End of cycle .
(3)do...while sentence
do...while General structure of statements
do // Do things first , To determine
{
Loop statement ; //do...while The loop statement of is executed at least once
}while( expression ); // After the loop statement , Then judge whether to execute the next cycle
do...while Statement break and continue
Usage and while The usage in the statement is consistent .
break:
#include <stdio.h>
int main()
{
int i = 10;
do
{
if (i == 5)
break;
printf("%d\n", i);
i--;
} while (i < 10);
return 0;
}
When i=5 When I met break, Jump straight out of the loop .
continue:
#include <stdio.h>
int main()
{
int i = 10;
do
{
if (i == 5)
continue;
printf("%d\n", i);
i--;
} while (i < 10);
return 0;
}
take break Change it to continue after , Then execute the code , Find print 10 9 8 7 6 Backward into the dead cycle . This is because of our adjustment part i-- stay continue Back , Cause the cycle to be stuck i=5, Only need to i-- Move to continue Just ahead .
goto sentence
goto The most common use of statement is to terminate the processing of the structure of the program nested in some depth .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 .( In theory, goto Statements are not necessary , In practice, there is no goto Statements can also easily write code .)
Program for setting password : Enter the password and confirm it , If the two passwords are inconsistent, re-enter , If it is the same twice, you will be prompted that the password is confirmed successfully .
#include<stdio.h>
#include<string.h>
int main()
{
char num1[10] = { 0 };// Save the first input password
char num2[10] = { 0 };// Store the second confirmation password
printf(" Please set your password :>");
again:
scanf("%s", num1);
printf(" Please confirm the password :>");
scanf("%s", num2);
if (strcmp(num1, num2)!=0)//stecmp Compare the contents of two strings
{
printf(" Input error , Please reset :>");
goto again;// here again You can customize , As long as it is consistent .
}
else
printf(" Input correct , Password confirmed :>\n");
return 0;
}
Want to use goto sentence , Need to be for goto Statement provides a label . For example, in the above code scanf Set a before the function again, When the two input results are different , perform goto again, The program will jump to scanf function , here again You can customize , As long as the names before and after are the same .goto Statement can jump anywhere in the main function , That's why goto When the sentence is bug The reasons that are easy to appear .
notes :
- strcmp Is a function used to compare the contents of two strings : Use format as strcmp( character string 1, character string 2), The return value is integer .
- When string 1 And string 2 The content of Agreement when ,strcmp The return value is 0;
- When string 1 Less than character string 2 when ,strcmp Return value <0;
- When string 1 Greater than character string 2 when ,strcmp Return value >0.(VS The compiler is smaller than returning -1, Equal to return to 0, Greater than return 1)
- Want to use strcmp Function needs to contain header file <string.h>, Otherwise, the compiler will alarm “strcmp” Undefined .
边栏推荐
- MySQL锁总结(全面简洁 + 图文详解)
- 透彻理解LRU算法——详解力扣146题及Redis中LRU缓存淘汰
- 1.C语言初阶练习题(1)
- fianl、finally、finalize三者的区别
- List set map queue deque stack
- FAQs and answers to the imitation Niuke technology blog project (III)
- Leetcode. 3. Longest substring without repeated characters - more than 100% solution
- 仿牛客技术博客项目常见问题及解答(三)
- [中国近代史] 第六章测验
- 6.函数的递归
猜你喜欢
There is always one of the eight computer operations that you can't learn programming
2.初识C语言(2)
Nuxtjs快速上手(Nuxt2)
8.C语言——位操作符与位移操作符
2.C语言初阶练习题(2)
5.函数递归练习
Questions and answers of "signal and system" in the first semester of the 22nd academic year of Xi'an University of Electronic Science and technology
View UI plus released version 1.3.0, adding space and $imagepreview components
Using spacedesk to realize any device in the LAN as a computer expansion screen
1.初识C语言(1)
随机推荐
Mode 1 two-way serial communication is adopted between machine a and machine B, and the specific requirements are as follows: (1) the K1 key of machine a can control the ledi of machine B to turn on a
Why use redis
更改VS主题及设置背景图片
2.C语言初阶练习题(2)
2.初识C语言(2)
Wei Pai: the product is applauded, but why is the sales volume still frustrated
IPv6 experiment
最新坦克大战2022-全程开发笔记-2
【手撕代码】单例模式及生产者/消费者模式
深度强化文献阅读系列(一):Courier routing and assignment for food delivery service using reinforcement learning
List set map queue deque stack
JS interview questions (I)
5.函数递归练习
Questions and answers of "basic experiment" in the first semester of the 22nd academic year of Xi'an University of Electronic Science and technology
【九阳神功】2017复旦大学应用统计真题+解析
View UI plus releases version 1.1.0, supports SSR, supports nuxt, and adds TS declaration files
简述xhr -xhr的基本使用
The overseas sales of Xiaomi mobile phones are nearly 140million, which may explain why Xiaomi ov doesn't need Hongmeng
4.分支语句和循环语句
Change vs theme and set background picture