Super complete & super detailed C language basic knowledge points "Branch and Loop" introductory package

A comprehensive and detailed summary of branching & looping knowledge points!

Hello everyone, this is Yaoyaozi, a college student who is working hard to learn computer knowledge. He is sharing his learning content here. I hope the knowledge and content shared can be helpful to you. There may be areas where the understanding is not deep and comprehensive, and the statements are inaccurate. I hope to give you valuable suggestions so that we can make progress and grow together!
Knowledge system map
picture:Insert image description here

C language structure (three types)

First of all, we need to know that C language is a structured programming language. C language has three structures, namely: sequential structure , selection structure , and loop structure.

·Sequential structure : The program proceeds in sequence from beginning to end, with no selectivity (certain parts of the code are executed and certain parts of the code are not executed), and certain parts of the code are not executed repeatedly.

#include <stdio.h>
int main()
{
    
      printf("hello word\n");
   printf("happy new year\n");

return 0;
}


·Selection structure : It is based on conditions to determine whether the program can be executed. So it is selective. The statement corresponding to the selection structure isselect statement, including if statements and switch-case statements .
for example:

#include<stdio.h>
int main()
{
    
      int i=0;
   printf("1+1=\n");
   scanf(%d",i);
   if(i=2)
   {
    
    
     printf("恭喜你回答正确\n");
   }
   else
   {
    
    
     printf("很遗憾,你回答错误\n")
   }
 return 0;
}

We can see that when i is equal to 2, the statement after if will be executed, and when i is not equal to 2, the statement after else will be executed.
Of course, this if statement will be discussed in detail later.

·The loop structure first loops, which is to let the code do one thing in a loop. The corresponding loop structure isloop statement, including while loop , for loop , do while loop .
for example:

#include<stdio.h>

int main()
{
    
    
  int i=1;
  while(i<=3)
  {
    
    
    printf("我真棒\n");
    i++}
  
  return 0;
}

The execution result of this code is three identical "I'm awesome".
In fact, it can be seen that both while and if are judged first and then executed, but while must be executed repeatedly. You can also see that loops help us accomplish things that need to be done repeatedly. Although it is three times here, what if it is fifty times? Wouldn't it be better to type "I'm awesome" fifty times without looping?
So the existence of loops makes sense.

branch statement

1. if statement

·Grammatical structure :
1,

//单分支
if(表达式)
{
    
    
  语句1}

Explanation: The expressions in parentheses can be relational expressions (referring to expressions with operators <, >, <=, >=, ==, !=), logical expressions (referring to operators with ||, &&, Expressions other than 1), numerical expressions (the operator is the assignment number =).

Statement 1 : It is the statement to be executed when the result of the expression in the brackets is non-0 (0 is false, non-0 is true).

Of course, there can be multiple statements here.

Grammatical structure 2.

//多分支语句(级联if语句)
if(表达式1{
    
    
语句1}
if else(表达式2{
    
    
语句2if else(表达式3{
    
    
语句3}
......
else(表达式n)
{
    
    
语句n:
}


A { } here is a code block, which is not necessarily a single statement. It can also contain multiple statements according to needs.

To put it
simply, nested if means that the statement after if is also one or more if statements, forming a nested form.
For example: Find the largest number among the three numbers a, b, and c.

//嵌套的if
#include<stdio.h>

int main()
{
    
    
  int a=3
  int b=2;
  int c=6;

  if(a>b)
  {
    
    
    if(c>a)
    {
    
    
      printf("c最大\n");
    }
    else
    {
    
    
      printf("a最大\n"):
    }
  }
  else (b>a)
  {
    
    
    if(c>b)
    {
    
    
      printf("c最大\n");
    }
    else
    {
    
    
      printf("b最大\n");
  }

return 0;  
}

Notice: 1. You can omit the braces when there is one clause, but you must add braces when there are multiple clauses.
2. There is no semicolon after the parentheses of the if statement.
3. There must be a semicolon after the statement to be executed within the if braces.
4. Else always matches the nearest if that does not match, which is referred to as the nearest- nearest principle .
Let's look at an example:

//悬空else问题
#include<stdio.h>
 int main()
 {
    
    
   int a=1;
   int b=2;
   
   if (b==3)
     if(a==1)
     printf("honesty");
   else
   printf("calculation");

return 0;
}

What do you think the result of running this code is?

If you think it is calculation
, then congratulations, you are wrong.
In fact, the first time I looked at this code, I thought it was very strange. Why are there two ifs? And from our beginner’s perspective, we will feel that the conditions of if are not met, so jump to else. , execute the result after else, and the first if is the same as else. But the computer doesn't think so. It will match else with the nearest unmatched if condition. When the if condition that matches it is not met, the statement following else will be executed.

So the execution result of this code is: nothing is executed.

Let's analyze it, b==3 is not satisfied, that is, this condition is false, and there is no else matching this if, then the compiler will automatically jump to return 0; that is, no result will be output.

But if you just want the first if and else of this code to match, or you don’t want to cause ambiguity, according to the above code, our original intention is to say that if b == 3, a == 1, output "honesty ", otherwise output "calculation", then we should add a pair of curly braces { } after if,
which is as follows

if(b==3)
{
    
    
   if(a==1)
  {
    
    
  printf("honesty"):
  }
}
else
{
    
    
printf("calculation");
}

As can be seen from the above, there are many benefits of adding curly braces, which will not cause ambiguity and make the code easier for readers to read and understand.
So as a good programming habit, we add curly braces to no matter how many statements follow if or else.

5. (Say important things three times!!!)
Don’t mistakenly write “==” in relational expressions as “="! ! !
Do not mistakenly write "==" in relational expressions as "="! ! !
Do not mistakenly write "==" in relational expressions as "="! ! !

Let's give an example

int i=0;
scanf("%d",i);
if(i==3)
{
    
    
  printf("星期三\n");
}

Only when we enter 3, the output result is "Wednesday", otherwise nothing is output.

int i=0;
scanf("%d",i):
if(i=3)
{
    
    
printf("星期三\n");
}

When we run this code, we will find that no matter what number we enter, the output result is always "Wednesday", which deviates from our ideal result.

explain:
The first thing we need to understand is when can the statement after if be executed. As mentioned before: when the expression result is non-0.

"==" is a relational operator, which represents an "equality relationship". Only when the data before and after the symbol are equal, the result of the expression will be non-0, and if they are not equal, it will be false. The statement after the if will be executed only when the expression result is non-zero. This is why "Wednesday" is printed only when 3 is entered.

"=" is the assignment number, which means assigning the value after the operator to the previous one. For example: a=b means assigning the value of b to a. It does not represent a relationship, but the action of assignment. Assignment is also a process of operation and has a result. The result of the assignment expression is the value on the right side of the assignment symbol! ! ! So the expression (i=3) means assigning 3 to i. The result of this expression is 3, non-0. The statement after if is executed, so no matter what is input, the result of this expression is non-0. Print "Wednesday".

2. switch-case statement

Syntax structure :

 switch(整形表达式)//括号里面表达式的结果必须为整形
//switch是表示判断
 {
    
    
  case 1://case后面不一定是数字,但也一定是整形常量表达式
  语句1;
  case 2://case相当于一个如果,根据switch判断从哪个case进入
  语句2...
  //花括号里面的为语句项,基本结构如上
 }

Note: What follows the case must be an integer constant expression. Note that it is a constant, not a variable!

Let’s start with the entire example: based on the numbers we input, output the corresponding day of the week.
How to express it using if statement?

#include<stdio.h>

int main()
{
    
    
  int i=0;//初始化
  scanf("%d",&i);

  if(i==1)
  {
    
    
    printf("星期一\n");   
  }
  else if(i==2)
  {
    
    
    printf("星期二\n");
  }
  else if(i==3)
  {
    
    
    printf("星期三\n");
  }
  else if(i==4)
  {
    
    
    printf("星期四\n");
  }
  else if(i==5)
  {
    
    
    printf("星期五\n");
  }
  else if(i==6)
  {
    
    
    printf("星期六\n");
  }
  else if(i==7)
  {
    
    
    printf("星期天\n");
  }
  else
  
  return 0;
}

The output is as follows
Insert image description here

Insert image description here

Use switch-case statement to express?

#include<stdio.h>

int main()
{
    
    
  int i=0;
  scanf("%d",i);

  switch(i)
  {
    
    
    case 1:
        printf("Monday\n");
    case 2:
        printf("Tuesday\n");
    case 3:
        printf("Wednesday\n");
    case 4:
        printf("Thursday\n");
    case 5:
        printf("Friday\n");
    case 6:
        printf("Saturday\n");
    case 7:
        printf("Sunday\n");
  }
 return 0;
}

It does feel more concise than if statements. But is this code correct? Or is it accurate?
Let's take a look at the running results:
Insert image description here
Insert image description here
inputting 7 is still normal. Why does inputting 3 output 5 results? Shouldn't it be Wednesday?
This will introduce a knowledge point: break and continue usage (continue will be discussed in the loop section later)
break:
means "stop and terminate"

There is a problem with the output of the above code because case is indeed the entrance. Entering from case3, the code is executed downwards. Can it be exported? In other words, the code will not break out of this system until all the codes after case 3 are executed. This is why everything from Wednesday to Sunday is printed. Our ideal output result is to input 3 and output Wednesday. That is to say, we want this code to break out of this system (or have an exit) after printing Wednesday, and no longer continue to print. Here we need to use "break" to accomplish this purpose, so that the code ends where it should end and jumps out of the system.

break is equivalent to a termination flag. When the code has the opportunity to encounter break, it will jump out of this system (here refers to switch-case). In summary, case determines the entry of the switch statement, and break determines the exit .
So let’s take a look at the improved code:
(Note: a semicolon is also required after break)

#include<stdio.h>

int main()
{
    
    
  int i=0;
  scanf("%d",i);

  switch(i)
  {
    
    
    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;
  }
 return 0;
}

The output is as follows, look, Perfect!
Insert image description here
reflection:1. Does each case have to correspond to a case?
·In fact, this is not the case. Just add break at the appropriate position or where you want to stop according to specific needs.
2. Is it okay to add break in the last case?
·As far as the compilation results are concerned, it actually has no impact whether the last case needs to be broken or not.
However, in order to modify the code next time (for example, if we need to add a case, we must add a break to the last case), it is more convenient and less error-prone, and as a good programming habit, we still add a break to the last case. The previous matching break.
3. What if the integer we input does not have a corresponding case corresponding to it?
·This requires the use of default, which means "default" in English. It is actually a default entry. When the input integer does not have a corresponding case, the default entry is used.
for example:

//将百分制成绩转换为等级制:
#include<stdio.h>

int main()
{
    
    
   int grade=0;
   printf("请输入成绩:>\n");
   scanf("d",&grade);
   int grade/=10;
   
   switch(grade)
   {
    
    
      case 10:
      case 9://这里也印证了不是每一个case都要匹配break
      printf("A\n");
      break;
      case 8:
      printf("B\n");
      break;
      case 7:
      printf("C\n");
      break;
      case 6:
      printf("D\n");
      break
      default://默认入口
      printf("E\n");
      break;
  }
   
   
return 0;
}

loop statement

1. while loop

Syntax structure :

while(表达式)
   {
    
    
    循环语句;//我们把这个大括号包括里面的内容称作“循环体”
   }

Note: There must be an opportunity to change conditions within the loop, otherwise it will be an infinite loop or an infinite loop (if what is needed is an infinite loop, I didn’t say (✿◕‿◕✿))
execution process :

Insert image description here
Break usage :
When there is a chance to execute break in the loop body, it will jump out of the loop body, end the loop, and continue to execute the following code downwards according to the program.
Continue usage :
When there is a chance to execute continue inside the loop, the code after continue (in the loop body) will no longer be executed. The program thinks that the loop is over and returns to the judgment part of while to start the next loop.

Let’s talk with examples:

#include<stdio.h>

int main()
{
    
    
  int i=1;
  
  while(i<=10)//判断进入循环体条件
  {
    
    
     printf("%d\n",i);
     i++;
  }
return 0;
}

Execution results:
Insert image description here
Let’s take a look at what happens when we add break :

#include<stdio.h>

int main()
{
    
    
    int i = 1;

    while (i <=10)
    {
    
    
        printf("%d\n", i);
        if (i == 3)
        {
    
    
            break;
        }
        i++;
    }
    return 0;
}

The execution result is as follows:
Insert image description here
Explanation: After executing the loop three times, i==3, then enter the if statement, encounter break, jump out of the loop body, no longer i++, and no longer enter the loop, so the execution result is 1 2 3. Take a look
again What will happen if break is replaced by continue :

#include<stdio.h>

int main()
{
    
    
    int i = 1;

    while (i <=10)
    {
    
    
        printf("%d\n", i);
        if (i == 3)
        {
    
    
            continue;
        }
        i++;
    }
    return 0;
}

The execution result is as follows: 1 2 3 3 3 3_ loop
Insert image description here
explanation: when i==3 after three loops, execute the if statement and encounter continue, then the code after continue (in the loop body) will no longer be executed, which is i++ , end this loop, and then start the next loop. Because i == 3 < 10, it enters the loop body and encounters continue... and so on, so the output result is a loop of 1 2 3 3_.

2. for loop:

Grammatical structures:

for(表达式1;表达式2;表达式3{
    
    
循环语句;
}

Expression 1 : Initialization part, that is, initializing the loop variable, determining the starting value of the loop variable (note: not creating a loop variable).
Expression 2 : The conditional judgment part determines when the loop variable terminates.
Expression 3 : Adjustment part, used to adjust loop variables.
Execution process :
Insert image description here

·Comparison with the while loop:
Expression 1 is equivalent to the initialization part outside the while loop, expression 2 is equivalent to the expression 1 after while, which are all conditional judgment parts, and expression 3 is equivalent to the condition adjustment part inside the while curly braces.
From the above, we can see that the for statement is more intuitive and easier to adjust and correct than the while statement.

Examples of differences:

  • while loop:
#include<stdio.h>

int main()
{
    
    
    int i = 1;

    while (i <=10)
    {
    
    
        printf("%d\n", i);
        if (i == 3)
        {
    
    
            continue;
        }
        i++;
    }
    return 0;
}

As mentioned above, the execution result of this code is 1 2 3 3 3...3 3_, the result of this infinite loop

  • for loop
#include<stdio.h>

int main()
{
    
    
    int i = 0;

    for(i=1;i<=10;i++)
    {
    
    
        printf("%d\n", i);
        if (i == 3)
        {
    
    
            continue;
        }
    }
    return 0;
}

Why are the execution results of this code different?
Insert image description here
Explanation: In fact, the fundamental reason is that the execution processes of while loops and for loops are different.

  • while loop: the code after continue i++ is not executed
  • for loop: There is no other code after continue, expr3 (i++) is still executed, so after i==3, continue ends the loop, but note that you still have to go to expr3 plus 1 first, then i ==4, and then continue the loop. Come to expr2 judgment, and then enter the loop body again and continue like this. What you get is not an infinite loop, but 1 2 3 4 5 6 7 8 9 10

Notice:

  • Do not modify loop variables within the for loop body to prevent the loop from losing control (turning into an infinite loop or infinite loop).
    For example:
#include<stdio.h>

int main()
{
    
    
    int i = 0;

    for(i=1;i<=10;i++)
    {
    
    
       
        if (i = 5)//注意:这里是赋值符号“=”,不是关系等于符号“==” 意思把5赋值给i
        {
    
    
            printf("%d\n", i);
        }
    }
    return 0;
}

The execution result is: 5 loop
Insert image description here
explanation : Because the first time you enter the loop or every time it loops, i is modified to 5<10 (although i++ is changed, it is modified to 5 after re-entering) and so on, so the output The result is a loop of 5.

  • It is recommended that the loop control variable (expr2) be written in the "front closed and then open interval" format.
#include<stdio.h>

int main()
{
    
    
    int i = 0;

    for(i=0;i<10;i++)
    {
    
    
            printf("%d\n", i);
    }
    return 0;
}

The way of writing i=0;i<10 is better than i=1;i<9
because the former way of writing 10 has a certain meaning:
1. Loop 10 times
2. Print 10 times
3. 10 elements

Some variations of the for loop :

  • omission:
int main()
{
    
    
  for(;;)
  {
    
    
     printf("I am chinese\n");
  }
}

1. The three parts of initialization, judgment and adjustment of the for loop can be omitted. But note that although the judgment part is omitted, it actually implies that the judgment condition is always positive.
2. If you are not very proficient, it is recommended not to omit it casually.
For example: (do not omit)

#include<stdio.h>

int main()
{
    
    
    int i = 0;
    int j = 0;
    
    for(i=0;i<10;i++)
    {
    
    
        for (j = 0; j < 10; j++)
        {
    
    
            printf("Good morning\n");
        }
    }
    return 0;
}

The execution results are as follows: 100 Good mornings
Insert image description here
(omitted)

#include<stdio.h>

int main()
{
    
    
    int i = 0;
    int j = 0;
    for(;i<10;i++)
    {
    
    
        for (;j < 10; j++)
        {
    
    
            printf("Good morning\n");
        }
    }
    return 0;
}

Output result: 10 Good mornings
Insert image description here
. Why is there not 100 here? Isn’t it just that i=0 and j=0 are omitted? The result should be 100 Good mornings.
This is the consequence of unskilled use of omission!
Explanation: First, i=0 enters the second loop. After the second loop is performed ten times, it exits the loop body and then enters the first loop. i=1, ready to enter the second loop. Note that j=10 at this time. In other words, you can't enter the second for loop at all! ! ! Because j is still equal to 0 before entering the second loop, unlike the version that is not omitted, there is no expr1 to re-initialize j to 0 when entering the loop body of j again! This is where the problem lies.

  • Two loop variables (rare)
//变种2
#include<stdio.h>

int main()
{
    
    
    int i = 0;
    int j = 0;
    for(i=0,j=0;i<3&&j<7;i++,j++)//&&表示“并且”的意思
    {
    
    
        printf("believe yourself\n");
    }
    return 0;
}

The output is as follows: 3 believe yourself
Insert image description here

3. do while loop

Grammatical structures:

//do while循环结构
do
   {
    
    
    循环体语句;
   }
while(表达式)//循环条件
   

Execute it at least once. The usage scenarios are limited, so it is rarely used.

Execution process: (Execute first and then judge)
Insert image description here
The above is all about the basic knowledge of branches and loops! I hope the content I talked about will be helpful to you. The mind map and flow chart were all made by myself. I hope it can help you remember and understand. The blogger himself is in his freshman year, and he is also trying to understand and explain from the perspective of a beginner. The explanation of branches and loops in C language may be inaccurate, but the purpose of blogging is not to record and share learning content. And knowledge! I hope that all students can give valuable opinions. I will be happy to hear other people's suggestions and understanding, so that we can make progress together! (❤ ω ❤)

Guess you like

Origin blog.csdn.net/Yaoyao2024/article/details/126618477