当前位置:网站首页>[branch and cycle] | | super long detailed explanation + code analysis + a trick game
[branch and cycle] | | super long detailed explanation + code analysis + a trick game
2022-07-03 05:38:00 【Sobtemesa】
Stay hungry. Stay foolish. ——Steve Jobs
Stay Hungry , stay foolish .

c Language is a structured programming language , It has three basic structures , Namely : Sequential structure , Selection structure , Loop structure .
C Language order structure is to let the program execute each item in order from beginning to end C The language code , Do not repeat any code , And don't skip any code .
C Language choice structure is also called branch structure , It's about letting the program “ Round the corner ”, Selective execution code ; let me put it another way , You can skip useless code , Only execute useful code .
C The language loop structure is to make the program “ Kill a rifle ”, Repeatedly execute the same piece of code .
The sequence structure will not be repeated , Today, let's focus on learning branch sentences ( Selection structure ) And loop statements .
First , Let's make clear two concepts first .
What is? sentence ?
C In language , Separated by a semicolon is a sentence .eg:
printf(" you are beautiful ");
a++;
; ------- Empty statement
What is? Sentence block ?
C In language , By a {} One or more statements enclosed , It is called a statement block . If there is only one statement in the statement block , You can omit it { }.
int main()
{
return 0;
}
Catalog
while Statement break and continue
Branch statement
if sentence
We need to do something when certain conditions are met , When the conditions are not met, no operation is carried out , At this time we can just use if sentence .

For example, judge whether a number is even .
int n=0;
scanf("%d",&n);
if ( n % 2 == 0)
{
printf( " It's even ");
}
return 0;
if-else sentence
if and else It's two new keywords ,if Meaning for “ If ”,else Meaning for “ otherwise ”, Used to judge conditions , And execute different statements according to the judgment results . Execute different code in different situations , thus Implement multi branch .

if( Judge the condition )
sentence 1;
else if( Judge the condition )
sentence 2;
else
sentence 2;
application :
Convert student grades .

In the air else
if When statements are nested , it is to be noted that if and else The problem of pairing .C Language policy ,else It's always the closest to it if pairing , for example :
int main()
{
int a = 0;
int b = 2;
if (a == 1)
if (b == 2)
printf("hehe");
else
printf("haha");
return 0;
}
What do you think is the output ?

analysis :else It's always the closest to it if pairing ,a=0, first if The statement does not enter at all , So no output .
Here we need to pay attention to our writing form , We need to develop a good code style . Revise it .

if Contrast of writing forms
Code 1 :
if(condition)
{
return x;
}
return y;
Code 2 :
if(condition)
{
return x;
}
else
{
return y;
}
Do these two codes express the same meaning ? If it's you, which code do you choose ?
Code three :
int num=1;
if(num==5)
{
printf("haha");
}
Code four :
int num=1;
if(5==num)
{
printf("haha");
}
If it's you, which code do you choose ?
Code 2、4 more intuitive , Good logic , It's not easy to make mistakes. , High readability .
practice :
1: Judge whether a number is odd
2. Print 1-100 Between the odd numbers

switch sentence
C Although there are no restrictions on language if else Number of branches that can be processed , But when there are too many branches , use if else It will be inconvenient to deal with , And it's prone to if else Pairing error . In this case , In general use switch Sentence instead .
switch( expression )
{
case Integer constant expression 1: sentence 1;
case Integer constant expression 2: sentence 2;
case Integer constant expression 3: sentence 3;
case Integer constant expression 4: sentence 4;
case Integer constant expression n: sentence n;
default: sentence n+1;
Operation process :
1. First, execute switch The expression after , Let its value be a
2. If a== Integer constant expression 1, Then follow All statements ; That is from “ sentence 1” Until “ sentence n+1”, and No matter what's in the back case Whether the match is successful .
3. If “ Integer constant expression 1” and a It's not equal , Just skip the... After the colon “ sentence 1”, Continue to compare the second one case、 Third case…… Once it is found to be equal to an integer value , Will execute all the following statements . hypothesis m and “ Integer constant expression 1” equal , Then we will “ sentence 5” Until “ sentence n+1”.
4) If you go to the last one “ Integer values n” No equal value was found , Then execute default After “ sentence n+1”.
What needs to be emphasized is , After matching with an integer value successfully , The statement of this branch and all subsequent branches will be executed .
break yes C A key word in a language , Designed to jump out of switch sentence . So-called “ Jump out of ”, Refer to Once encountered break, I'm not going to execute it anymore switch Any statement in , Include statements in the current branch and statements in other branches ; in other words , Whole switch Execution is over , Then the whole... Will be executed switch Later code .
practice :
int main()
{
int n = 1;
int m = 2;
switch (n)
{
case 1:
m++;
case 2:
n++;
case 3:
switch (n)
{
case 1:
n++;
case 2:
m++;
n++;
break;
}
case 4:
m++;
break;
default:
break;
}
printf("m=%d n=%d\n", m, n);
}

loop
So-called loop (Loop), Is to execute the same piece of code repeatedly .
while loop
while( expression )
{
Sentence block ;
}
Operation process : To calculate “ expression ” Value , True value is true. ( Not 0) when , perform “ Sentence block ”; After execution “ Sentence block ”, Evaluate the expression again , If it is true , Carry on “ Sentence block ”…… This process will be repeated all the time , Until the value of the expression is false (0), Just exit the loop , perform while Later code .
while The whole idea of circulation : Set a loop condition with variables , That is, an expression with variables ; Add an additional statement to the loop body , Let it change the value of the variable in the loop condition . such , As the cycle goes on , The value of the variable in the loop condition will also change , There will be a moment , The cyclic condition no longer holds , The whole cycle is over .

while Statement break and continue
break: Permanent termination of cycle .
continue: Terminate the loop .
int main()
{
int i = 1;
while (i <= 10)
{
if (i == 5)
continue;
printf("%d", i);
i++;
}
return 0;
}
What is the output of the code ?

practice :
1. Look at two codes

notes :1.EOF------ End of file flag
2.getchar When reading fails, it will return EOF
3. Characters returned , Essentially, ASCII Code value , Is an integer , It can be stored in ch in
4.getchar Functions do more than just return normal characters , And return to EOF, Its value is -1

2. Analyze the code below



scanf/getchar It's all in Input buffer Get the input value in ,scanf When getting the input value , Take away \0 The value of the former , Assigned to an array , So the next one getchar when , Take the rest from the input buffer \0, So no longer wait for input .
Modify the code :

This operation is still flawed :


modify :

for loop
for The general form of the cycle is :
for( expression 1; expression 2; expression 3)
{
Sentence block
}
Its operation process is :
1) Execute first “ expression 1”.
2) Re execution “ expression 2”, If it's true ( Not 0), Then execute the loop body , Otherwise end the cycle .
3) Execute after the loop body “ expression 3”.
4) Repeat steps 2) and 3), until “ expression 2” The value of is false , Just close the loop .
In the above steps ,2) and 3) It's a cycle , Will repeat ,for The main function of a statement is to continuously execute steps 2) and 3).

continue problem :

continue Skip the following code , Went to the adjustment part , Make the loop variable adjust , It is not easy to cause a dead cycle .
do-while loop
do-while The general form of the cycle is :
do
{
Sentence block
}while( expression );
do-while Circulation and while The difference with cycles is that : It will be executed first “ Sentence block ”, Then judge whether the expression is true , If it is true, it continues to loop ; If it is false , Then stop the cycle . therefore ,do-while The loop must be executed at least once “ Sentence block ”.
continue problem :

Code practice :
1. Calculation n The factorial :

2. Calculation 1!+2!+3!+.....+n!


3. Find numbers in an ordered array n

Two points search

3. Write code , Demonstrate that multiple characters move from both ends to converge in the middle

4. Write code to achieve , Simulate user login scenarios , And can only log in three times .

5. Guess the number game
brief introduction :
rand() function
function : Returns a pseudo-random number . It's a pseudo-random number , Because in the absence of other operations , Run the same program every time , call rand The random number sequence is fixed ( Not really “ Random ”).
In order to make rand The results are more “ really ” some , That is to make the return value more random ( uncertainty ),C Language in stdlib.h It is also provided srand function , Through this function, you can set a random number seed , Generally, the number of milliseconds of the current time is used as the parameter . adopt time(NULL) You can get the millisecond value of the current time ( This function is located in time.h) in . If there is no random number of seeds ,rand() Function is called , Automatically design random number seeds as 1. Same random seed , The random number generated each time will also be the same .
Use rand The process can be summarized as :
1 call srand(time(NULL)) Set random number seed .
2 call rand Function to get one or a series of random numbers .
It should be noted that ,srand Just in all rand Before calling , It can be called once , There's no need to call it more than once .
void menu()
{
printf("**********************************\n");
printf("****1.paly************************\n");
printf("****0.exit************************\n");
printf("**********************************\n");
printf("**********************************\n");
}
void play()
{
int input = 0;
int random_num = rand() % 100 + 1;
while (1)
{
printf(" Please enter a number :");
scanf("%d", &input);
if (input > random_num)
{
printf(" Guess the \n");
}
else if (input < random_num)
{
printf(" Guess a little \n");
}
else
{
printf(" congratulations , Guessed it ");
break;
}
}
}
int main()
{
int input = 0;
int random_num = rand() %100 + 1;
do
{
menu();
printf(" Please select (0/1):");
scanf("%d", &input);
switch (input)
{
case 0:
break;
case 1:
play();
break;
default:
printf(" Input error ");
}
} while (input);
return 0;
}
A trick game
( Send the document to your friends , Feel the happiness of life ~)
goto sentence
goto The most common use of statements is Jump out of two or more loops . But due to the goto Statements can easily cause code confusion , Maintenance and reading difficulties , much-maligned , Not recommended , and goto Loops can be completely replaced by other loops .
Now let's use goto Play a little game

Redeposit failed Upload again Cancel
no need goto It can also be used. while

Redeposit failed Upload again Cancel
The end .
Happy everyday ~

边栏推荐
- Installing altaro VM backup
- 2022.DAY592
- Go practice -- use redis in golang (redis and go redis / redis)
- Redis 入門和數據類型講解
- [set theory] relational closure (relational closure related theorem)
- Why is go language particularly popular in China
- 【无标题】
- (subplots usage) Matplotlib how to draw multiple subgraphs (axis field)
- Webrtc native M96 version opening trip -- a reading code download and compilation (Ninja GN depot_tools)
- (perfect solution) how to set the position of Matplotlib legend freely
猜你喜欢

Configure DTD of XML file

Redis使用Lua脚本简介

Simpleitk learning notes

2022.DAY592

Webrtc native M96 version opening trip -- a reading code download and compilation (Ninja GN depot_tools)

Classification and discussion of plane grab detection methods based on learning

一起上水碩系列】Day 9

Webrtc M96 release notes (SDP abolishes Plan B and supports opus red redundant coding)

Skip table: principle introduction, advantages and disadvantages of skiplist

Export the altaro event log to a text file
随机推荐
MySQL startup error: several solutions to the server quit without updating PID file
Configure and use Anaconda environment in pycharm
Redis使用Lua脚本简介
Go practice -- use JWT (JSON web token) in golang
Intégration profonde et alignement des séquences de protéines Google
How to set up altaro offsite server for replication
Webrtc protocol introduction -- an article to understand ice, stun, NAT, turn
Redis 入门和数据类型讲解
PHP笔记超详细!!!
Deploy crawl detection network using tensorrt (I)
期末复习(day3)
Redis encountered noauth authentication required
Analysis of the example of network subnet division in secondary vocational school
Interview question -- output the same characters in two character arrays
ES 2022 正式发布!有哪些新特性?
Deep embedding and alignment of Google | protein sequences
Redis expiration elimination mechanism
Common interview questions of microservice
2022.6.30DAY591
Jetson AGX Orin 平台移植ar0233-gw5200-max9295相机驱动



