当前位置:网站首页>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
 Insert picture description here

Selection structure

Judge the given condition , Then decide the execution code according to the judgment result
 Insert picture description here
 Insert picture description here

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

 Insert picture description here

#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
 Insert picture description here

#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

 Insert picture description here

#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
 Insert picture description here

if Be careful

Any value is true or false
 Insert picture description here

When if else When there is only one statement after , if else The following braces can be omitted ( Not recommended )
 Insert picture description here
When if else When the following braces are omitted , else Will automatically contact the nearest one if matching
 Insert picture description here
If if else The braces are omitted , Then you can't define variables later
 Insert picture description here
 Insert picture description here

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

 Insert picture description here

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
 Insert picture description here
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
 Insert picture description here
Be careful :

  1. 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
  2. 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)
  3. case The values of the following constant expressions cannot be the same
  4. case Then you want to define variables , Must give case Add braces case 1:{ Code }
  5. 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
  6. switch in default It can be omitted
  7. 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
 Insert picture description here
 Insert picture description here
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 "
 Insert picture description here
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

 Insert picture description here
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 )
     Insert picture description here
    while Circular execution flow
  1. First of all, we will judge " Cycle control conditions " Is it true , If false, skip directly to the end of the loop statement
  2. If " Cycle control conditions " It's true , Perform a loop body , Then judge again " Cycle control conditions " Is it true , For real, continue
  3. Execution loop body , Jump out of loop for false
  4. Repeat the above operation , until " Cycle control conditions " Until it's false

 Insert picture description here

#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;
}

  1. Judge whether the cycle control condition is true , here 0 < 3 It's true
  2. Execute the code in the loop body , Print " bullets "
  3. perform " A statement that can end a loop " count = 1
  4. Judge whether the cycle control condition is true again , here 1 < 3 It's true
  5. Execute the code in the loop body , Print " bullets "
  6. perform " A statement that can end a loop " count = 2
  7. Judge whether the cycle control condition is true again , here 2 < 3 It's true
  8. Execute the code in the loop body , Print " bullets "
  9. perform " A statement that can end a loop " count = 3
  10. Judge whether the cycle control condition is true again , here 3 < 3 For false , Skip loop statements
  11. 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

 Insert picture description here
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

 Insert picture description here
Example
 Insert picture description here
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 )
 Insert picture description here
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

 Insert picture description here
 Insert picture description here

#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

  1. 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
  2. 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
  3. stay for Loop initializes the variables defined in the expression , Only in for After the loop {} Medium visit
  4. 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
 Insert picture description here
 Insert picture description here
break matters needing attention :

  1. break Leave the scope of application (for , switch), Existence is meaningless
  2. In a multi-level cycle , One break The statement just jumps out one level
  3. 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
 Insert picture description here

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
 Insert picture description here
 Insert picture description here
 Insert picture description here

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
 Insert picture description here
 Insert picture description here
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 :

  1. Generally, the nesting of loops should not exceed three layers , Otherwise, it's hard to maintain , Disaster.
  2. 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
  3. 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

 Insert picture description here
 Insert picture description here
 Insert picture description here
 Insert picture description here

 Insert picture description here

give the thumbs-up - Collection - Focus on - Easy to review and receive the latest content in the future
There are other questions to discuss in the comments section - Or believe me - I will reply as soon as I receive it
thank , coordination , I hope my efforts will help you ^_^

disclaimer : Part of the material in this paper comes from the Internet , The copyright belongs to the creator , If articles exist / picture / Improper use of audio and video , Please feel free to contact me by private letter .
原网站

版权声明
本文为[Hu Anmin]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207041818598452.html

随机推荐