[elementary c language] branch and loop statements

I preface

If you and I are also a beginner of c language, this article will take you to a detailed and in-depth understanding of branch and loop statements. Don't say much, now! Start.

1. What is a statement?

c language can be divided into the following five categories:
1. Expression statement
2. Function call statement
3. Control statement
4. Compound statement
5. Empty statement

Among them, the common branches and loops belong to control statements. What is control statements? Control statements are used to control the execution process of the program to realize various structural modes of the program. They are composed of specific statement definer. C language has nine kinds of control statements.
It can be divided into the following three categories:

  1. Conditional judgment statements are also called branch statements: if statements and switch statements;
  2. Circular execution statements: do while statement, while statement and for statement;
  3. Turn statements: break statements, goto statements, continue statements, and return statements.

The above are the key contents for us to learn c language. We need to firmly grasp and skillfully use it

II Branch statement (select structure)

Let's start with a vivid example:
If you study hard, you can get a good offer and reach the peak of your life.
If you don't study, graduation is unemployment. Go home and sell sweet potatoes.
This is the choice!
After understanding choice, we need to learn the syntax of choice structure

1.if statement

1.1 syntax structure (the following is the syntax structure of if statement)

(1) The simplest if structure

#include<stdio.h>
int main(){
	if(expression)
	   Statement 1;
    else
       Statement 2; 	   	 
	return 0;
}

(2) Multi branch if structure

if(Expression 1)
    Statement 1;
else if(Expression 2)
    Statement 2;
else
    Statement 3;

example:

#include <stdio.h>
int main()
{
 int age = 0;
    scanf("%d", &age);
    if(age<18)
   {
        printf("juvenile\n");
   }
    else if(age>=18 && age<30)
   {
        printf("youth\n");
   }
    else if(age>=30 && age<50)
   {
    printf("middle age\n");
   }
    else if(age>=50 && age<80)
   {
        printf("old age\n");
   }
    else
   {
        printf("God of Longevity\n");
   }
    
}

What needs to be explained here is that the statement after if or else can be one or more. If it is multiple, it must be caused by the {} structure. If it is one, it doesn't depend on your mood (funny)

1.2 other matters needing attention (key points)

If the result of the expression is true, the statement executes.
How to express true and false in C language?
A: 0 means false, and non-0 means true.
Note: (the following is my personal understanding)

If the conditional sentence is true, then the value is non-zero
If the conditional sentence is false, then the value is non-zero

After understanding this rule, the problem becomes much clearer
 At the beginning of school c In the process of language, some beginners often make some careless mistakes
 for example if(b==2)I often lose one=Become if(b=2)
Explanation: the first sentence is a judgment sentence, judgment b Is equal to 2, representing the value 0 or 1. The second is the assignment sentence, which will b The operation with a value of 2 b After assignment, b The value of is used as a condition to judge whether the statement is true or false, and the statement is true (non-0)

Therefore, in order to avoid some simple problems, we can write it as if(2==b). In this way, even if you write it wrong and write it as if(2=b), the compilation will not pass. In this way, you can quickly find and modify bug s.

< a gorgeous split line passed and ate two bites of code >

Suspended else problem
Next, ladies and gentlemen, please take a look at a situation

#include <stdio.h>
int main()
{
    int a = 0;
    int b = 2;
    if(a == 1)
        if(b == 2)
            printf("hehe\n");
    else
        printf("haha\n");
    return 0; }

What should be the output result of this situation?
In fact, nothing is output. Why on earth is this?
The reason is that else matches the nearest if
Therefore, else in the title matches if (b==2), so the output result is not

I personally dislike this situation, because the readability of this code is too poor. If we have a job interview, we'd better not write this bad code, otherwise it will be easily pass ed off. Therefore, we can improve this code to enhance its readability

The improved code (in this case, is the code much clearer and standardized 😊)

#include <stdio.h>
int main()
{
    int a = 0;
    int b = 2;
    if(a == 1){
        if(b == 2)
            printf("hehe\n");
        else
            printf("haha\n");
    }
    return 0; 
}

2.switch structure

The switch statement is also a branch statement.
It is often used in the case of multiple branches.

Let's take chestnuts for example to understand the switch structure in advance

For example:
Input 1, output Monday
Input 2, output Tuesday
Input 3, output Wednesday
Input 4, output Thursday
Input 5, output Friday
Input 6, output Saturday
Input 7, output Sunday

Some smart friends may have found that these are several if... else structures
Yes, in a sense, this is the combination of multiple if... else structures
However, if we use the switch structure, the readability of the code will be further improved, and it will be very beautiful

2.1 switch syntax structure

switch(Integer expression) {
    case Constant expression;
    sentence;
    //breakï¼›
}

ok, brothers, I believe you all understand the grammar. Let me give you another chestnut

Enter the day of the week and ask for the day of the week

The following is the code I wrote when I first learned it

#include <stdio.h>
int main()
{
    int day = 0;
    scanf("%d",&day)
        switch(day)
   {
        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; 
 }

At that time, I thought this was a small dish, but it was fishy when running. You can try it

Don't think about it. It must be a bug. Later, I learned about break through the textbook.

2.2 break

In the switch statement, we can't directly implement the branch. Only when we use it with break can we realize the real branch.

Take our code further

#include <stdio.h>
int main()
{
    int day = 0;
    switch(day)
   {
        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; }

When the input is 1, case 1 is encountered to execute the statement and directly break out of the branch
When the input is 2, case 2 will execute the statement, and break will jump out of the branch
...
And so on
How does the error code we write work?
I found the flow chart and pad chart through the teaching materials of Jilin University, which is convenient for everyone to understand

So is break a must?
Obviously not. In some cases, reasonably adding and removing break can make the code more concise
Suppose we change the requirements

  1. Input 1-5 and output "weekday";
  2. Input 6-7 and output "weekend"

Our code can be written as

#include <stdio.h>
//switch code demonstration
int main()
{
    int day = 0;
    switch(day)
   {
        case 1: 
         case 2:
        case 3:
        case 4:
        case 5:
            printf("weekday\n");
            break;
        case 6:
        case 7:
            printf("weekend\n");
            break;
   }
    return 0; }

In this case, will it be more convenient!

Good habit of programming
Add a break statement after the last case statement.
(this is written to avoid forgetting to add a break statement after the last previous case statement.).

As like as two peas, the 2.3 defalut clause is the same as case.

What if the expressed value does not match the values of all case tags?
In fact, it's nothing. The structure is that all statements are skipped.
The program will not terminate or report an error, because this situation is not considered an error in C.
But what if you don't want to ignore the values of expressions that don't match all tags?
You can add a default clause to the statement list and put the following tag
default:
Write where any case label can appear.
When the value of the switch expression does not match the value of all case tags, the statement after the default clause will be executed.
Therefore, only one default clause can appear in each switch statement.
However, it can appear anywhere in the statement list, and the statement flow executes the default clause like a case tag.

Good programming habits
It's a good habit to put a default clause in each switch statement. You can even add a break after it.

The article is a little long, to be continued.

Keywords: C Back-end

Added by hansford on Mon, 17 Jan 2022 17:16:06 +0200