After mieba snapped his fingers, I learned the "branch and loop statements" of C language

🌟 preface

Hello, I'm Edison 😎

The last article said that we should sort out the whole series of C language;

So I'm not idle for three days on New Year's day. No, today we start our second "branch statements and circular statements";

Let's get it!

The link to the previous article is here: Roommates only need a king's time to get started with "C language"
 
🔥 This article ranks first in the field and second in the hot list; Recommended reading priority 👆

🛫 Send a word to all those who are working hard: you don't have to turn over against the wind, but you must be born into the sun 🌅

Objectives of this chapter

The "branch and loop statements" of C language are explained in depth, and the individual difficulties are analyzed in depth;
 
And the corresponding example exercises will be carried out at the end of the paper

1. What is a statement?

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

Control statements are introduced later in this article.

Control statements are used to control the execution flow of the program to realize various structural modes of the program, which 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.

2. Branch statement (select structure)

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!

🍑 2.1 if statement

What is the grammatical structure of the if statement?

Grammatical structure 👇

//Single branch
if(expression)
    sentence;
    
//if and else   
if(expression)
    Statement 1;
else
    Statement 2;

//Multi branch    
if(Expression 1)
    Statement 1;
else if(Expression 2)
    Statement 2;
else
    Statement 3;

Let's look at a single branch

Code example 📝

#include <stdio.h>

int main()
{
    int age = 0;
    scanf("%d", &age);
    if (age < 18)
    {
        printf("under age\n");
    }
}

Operation results 👇

When the conditions are met, it will be executed;

When the conditions are not met, it will not be executed;

What if and else?

#include <stdio.h>

int main()
{
    int age = 0;
    scanf("%d", &age);
    if (age < 18)
    {
        printf("under age\n");
    }
    else
    {
        printf("adult\n");
    }
}

Operation results 👇

Age > 18, execute if statement;

Age < 18, execute else statement;

What about multiple branches?

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

&&: understandable and equivalent to meeting about & & conditions at the same time;
 
Age > = 18 & & age < 30: age must be greater than or equal to 18 and less than 30;
 
As for the & & operator, I will talk about it in the following articles. Don't worry here;

Operation results 👇

age = 45;

Explain: if the result of the expression is true, the statement executes.
 
How to express true and false in C language?
 
0 means false, and non-0 means true.

🎃 Important: if the condition holds and multiple statements are to be executed, how should code blocks be used.

#include <stdio.h>

int main()
{
    if(expression)
   	{
        Statement list 1;
   	}
    else
   	{
        Statement list 2;
   	}
    return 0;
}

The pair {} here is a code block.
 
So why use {} code blocks?
 
Because if can only control the statement closest to it. If you want to control multiple statements, use {} braces;

🍎 Suspended else

When you write the following code 📝

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

Guess what the execution result of this code is?
 
I guess some students will say: print haha on the screen;
 
Isn't it? Let's run and have a look

As a result, nothing was printed;
 
Because else is matched with if (b == 2), not if (a == 1);
 
Therefore, when the condition in the if (a == 1) statement is false, the if (b == 2) statement will not be executed, and the matching else statement will not be executed.

How to modify this code?

It's very simple. Just add {}

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

Operation results 👇

Else matching: else matches the nearest if;
 
Proper use of {} can make the logic of the code clearer;
 
So code style is very important.

🍎 Comparison of if writing forms

//Code 1
if (condition) {
    return x;
}
return y;

//Code 2
if(condition)
{
    return x;
}
else
{
    return y;
}

//Code 3
int num = 1;
if(num == 5)
{
    printf("hehe\n");
}

//Code 4
int num = 1;
if(5 == num)
{
    printf("hehe\n");
}

So how do we choose?
 
Code 2 and code 4 are better, the logic is clearer and less error prone.

🍎 Exercises

1. Judge whether a number is odd
 
2. Output odd numbers between 1 and 100

🍑 2.2 switch statement

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

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

If I write if else if ... Is the form of else if too complicated?

Therefore, there must be a different grammatical form, which is the switch statement.

switch(Integer expression)
{
    Statement item;
}

What are statement items? Are some case statements

case Integer constant expression:
    sentence;

🍎 break in switch statement

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

For example:

#include <stdio.h>

int main()
{
    int day = 5;
    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;
}

results of enforcement 👇


What if you don't add break?

When day=5, the program will execute successively under the statement case 5, which is obviously not what we want. We want the program to print only Friday;
 
Therefore, in order to make the program terminate after case 5, we need the keyword break to jump out of the program.
 
Now you know the importance of break!

But sometimes our needs change:

Input 1-5 and output weekday;
 
Input 6-7 and output weeken;

So our code should be implemented as follows:

#include <stdio.h>

int main()
{
    int day = 6;
    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;
}

results of enforcement 👇

Input 1

Input 6

The actual effect of the break statement is to divide the statement list into different parts.

🎃 Good programming habits

Add a break statement after the last case statement.
 
You can avoid forgetting to add a break statement after the last previous case statement.

🍎 default clause

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;
 
Write the tag default:, where any case tag can appear.

So what does this structure mean?

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 runs through the default clause like a case tag.

Code example 📝

#include <stdio.h>

int main()
{
    int day = 0;
    scanf("%d", &day);
    switch (day)
    {
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
        printf("weekday\n");
        break;
    case 6:
    case 7:
        printf("weekend\n");
        break;
    default:
        printf("Input error,Please re-enter\n");
    }
    return 0;
}

results of enforcement 👇

Input 3

Input 7

Input 10

🎃 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;
 
Whether to add break after case depends on the logic.

🍎 practice

Think about it 🤔, What is the execution result of the following code?

#include <stdio.h>

int main()
{
    int n = 1;
    int m = 2;
    switch (n)
   {
    case 1:
            m++;
    case 2:
            n++;
    case 3:
             switch (n)
           {//switch allows nested use
             case 1:
                    n++;
             case 2:
                    m++;
                    n++;
                    break;
           }
    case 4:
            m++;
             break;
    default:
             break;
   }
    printf("m = %d, n = %d\n", m, n);
    return 0;
}

3. Circular statement

while Loop
 
for loop
 
do while loop

🍑 3.1 while loop

We have mastered the if statement;
 
When the conditions are met, the statement after the if statement is executed, otherwise it is not executed. But this statement will be executed only once.
 
But we find that many practical examples in life are: we need to complete the same thing many times.
 
So what do we do?

C language introduces us: while statement, which can realize loop.

//while syntax structure

while(expression)
 	Loop statement;

Flowchart of while statement execution

Note: expr is an expression; stmt is a circular statement;

For example, we implement:

Print numbers 1-10 on the screen

Code example 📝

#include <stdio.h>

int main()
{
    int i = 1;
    while (i <= 10)
    {
        printf("%d ", i);
        i = i + 1;
    }
    return 0;
}

results of enforcement 👇


This code has helped me understand the basic syntax of the while statement.

🍎 break and continue in the while statement

🍅 break introduction

#include <stdio.h>

int main()
{
    int i = 1;
    while (i <= 10)
    {
        if (i == 5)
            break;
        printf("%d ", i);
        i = i + 1;
    }
    return 0;
}

results of enforcement 👇


When i == 5, the if condition is true, the program reads break and jumps out of the loop.

Summary: the role of break in the while loop

In fact, as long as a break is encountered in the cycle, all the later cycles will be stopped and the cycle will be terminated directly.
 
Therefore, the break in while is used to permanently terminate the loop.

🍅 continue introduction

#include <stdio.h>

int main()
{
	int i = 1;
	while (i <= 10)
	{
		i = i + 1;
		if (i == 5)
			continue;
		printf("%d ", i);
	}
	return 0;
}

results of enforcement 👇


When i == 5, if continue is encountered, the program directly jumps to the judgment part of the while statement and does not execute the following print statement.

Improper use of continue may cause an endless loop 👇

#include <stdio.h>

int main()
{
    int i = 1;
    while (i <= 10)
    {
        if (5 == i)
            continue;
        printf("%d ", i);
        i ++;
    }
    return 0;
}

results of enforcement 👇


When i=5, print and i + + do not execute; Directly return to the judgment part of i < = 10;
 
Then i is still equal to 5 at this time, so print: 1 2 3 4... Dead cycle

Summary: the role of continue in the while loop

continue is used to terminate this cycle;
 
That is, the code behind continue in this loop will not be executed, but directly jump to the judgment part of the while statement; Determine the inlet of the next cycle.

🍎 getchar and putchar

getchar: get characters from the keyboard;

putchar: print characters to the screen

Let's look at a code example 📝

#include <stdio.h>

int main()
{
 int ch = 0;
 while ((ch = getchar()) != EOF)
       putchar(ch);
    return 0;
}

results of enforcement 👇

Enter A and it will print A to the screen

Enter Abc and it will print Abc to the screen

Enter 123 and it will print 123 to the screen

You will find that no matter what we enter, it will be printed on the screen, so how to exit?
 
Just enter: Ctrl+z

So what exactly does this code mean? Why can Ctrl+z stop typing?

First, let's look at the above code. We can see that there is a problem in the judgment part of while= EOF;
 
EOF, the full name is: end of file, which means the sign of the end of the file;
 
When we go to the definition of EOF in VS2019, we can see that its value is - 1

When the program runs, our getchar starts reading characters;
 
EOF will be returned when getchar reading fails;
 
So why do the returned characters go into ch of type int?
 
Very simple, because the returned character is essentially a character, an ASCII value, and an integer;
 
The getchar function returns not only normal characters, but also EOF, that is - 1;
 
So put the return value in the shaping variable,

At this time, you may have questions, don't you read characters? Why is it possible to enter an integer variable like 123?

Note that 1, 123, etc. here are not integer variables;
 
Remember the ASCII code table in Chapter 1?

Because the getchar function is used to read characters;
 
Therefore, what it reads is character 1, not integer 1, and the integer number corresponding to character 1 is 49;
 
Do you understand?

Suppose, write a program to realize the user's login scenario

#include <stdio.h>

int main()
{
	int ch = 0;
	char password[20] = { 0 };
	printf("Please input a password>:");
	
	scanf("%s", password);
	
	printf("Please confirm the password>:\n");
	
	ch = getchar();
	if (ch == 'Y')
	{
		printf("Confirmation successful\n");
	}
	else
	{
		printf("Confirmation failed\n");
	}

	return 0;
}

Operation results 👇

As you can see, I haven't confirmed my password yet, so I am prompted that the confirmation failed

Why?

In fact, our scanf and getchar seem to read data from the keyboard;
 
In fact, it reads data from the input buffer;

First, scanf found that there was nothing in the input buffer, so I typed: abcdef\n;
 
Then put abcdef\n into the input buffer;
 
At this time, scanf finds something in the input buffer and takes away abcdef; And put it into the password array;
 
At this time, the input buffer is left \ n;
 
Next, print the confirmation password;
 
When getchar reads, it finds that there is another \ n in the input buffer, so it takes it directly and puts it into ch;
 
Then enter the if statement, \ n! = ' Y ', so the program goes else, and the confirmation fails;
 
So there was no waiting in the whole process!

How to modify the code?

When scanf takes away the password, it must ensure that the input buffer is empty;
 
So we need to clean up \ n;

Code example 📝

#include <stdio.h>

int main()
{
	int ch = 0;
	char password[20] = { 0 };
	printf("Please input a password>:");
	scanf("%s", password);
	
	while ((ch = getchar()) != '\n')
	{
		;
	}

	printf("Please confirm the password(Y/N)>:");
	ch = getchar();

	if (ch == 'Y')
	{
		printf("Confirmation successful\n");
	}
	else
	{
		printf("Confirmation failed\n");
	}

	return 0;
}

Operation results 👇

Enter the password in the form of number + letter + space;

Summary:

The value of EOF is - 1;
 
When getchar reads characters, if Ctrl+z is encountered,
 
Indicates that reading fails, and an EOF or - 1 will be returned
 
Both getchar and scanf read things from the input buffer;

Sister Li 😏

🍎 practice

Think about it 🤔, What is the execution result of the following code?

#include <stdio.h>

int main()
{
    char ch = '\0';
    while ((ch = getchar()) != EOF)
    {
        if (ch < '0' || ch > '9')
            continue;
        putchar(ch);
    }
    return 0;
}

🍑 3.2 for loop

We already know the while loop, but why do we need a for loop?

First, let's look at the syntax of the for loop

🍎 grammar

for(Expression 1; Expression 2; Expression 3)
 	Loop statement;

Expression 1 is the initialization part, which is used to initialize the of the loop variable.
 
Expression 2 is a condition judgment part, which is used to judge the termination of the cycle.
 
Expression 3 is the adjustment part, which is used to adjust the loop conditions.

🍎 flow chart


Look at a practical problem

Use the for loop to print numbers 1-10 on the screen.

#include <stdio.h>

int main()
{
    int i = 0;
    
    //for(i=1 / * initialization * /; i < = 10 / * judgment part * /; i + + / * adjustment part * /)
    for (i = 1; i <= 10; i++)
    {
        printf("%d ", i);
    }
    return 0;
}

results of enforcement 👇

Now let's compare the for loop with the while loop;

int i = 0;

//To achieve the same function, use while
i=1;//Initialization part
while(i<=10)//Judgment part
{
 	printf("hehe\n");
 	i = i+1;//Adjustment part
}

//To achieve the same function, use for
for(i=1; i<=10; i++)
{
 	printf("hehe\n");
}

It can be found that there are still three necessary conditions for the loop in the while loop;
 
However, due to the problem of style, the three parts are likely to deviate far, so the search and modification is not centralized and convenient.
 
Therefore, the style of the for loop is better. The for loop is also used the most frequently.

🍎 break and continue in the for loop

We found that break and continue can also appear in the for loop;
 
Their meaning is the same as in the while loop, but there are still some differences.

Code one 📝

#include <stdio.h>

int main()
{
    int i = 0;
    for (i = 1; i <= 10; i++)
    {
        if (i == 5)
            break;
        printf("%d ", i);
    }
    return 0;
}

results of enforcement 👇


When i=5, enter if statement judgment, and break terminates the whole loop;
 
So the break in the for loop is the same as the break in the while loop.

Code two 📝

#include <stdio.h>

int main()
{
    int i = 0;
    for (i = 1; i <= 10; i++)
    {
        if (i == 5)
            continue;
        printf("%d ", i);
    }
    return 0;
}

results of enforcement 👇


When i=5, continue jumps out of printf, does not print, and then goes to the adjustment part i + +; At this time, i=6;
 
Continue in the for loop is to jump out of the code behind continue and go to the adjustment part to adjust the loop variables, which is not easy to cause an endless loop.

🍎 Loop control variable of for statement

proposal 🤔

1. Loop variables cannot be modified in the for loop body to prevent the for loop from losing control.
 
2. It is suggested that the value of the loop control variable of the for statement should be written in the interval before closing and after opening.

What is the front closed and back open interval?

int i = 0;
//Front closed and back open
for(i=0; i<10; i++)
{}

//Both sides are closed intervals
for(i=0; i<=9; i++)
{}

🍎 Some variants of the for loop

📝 Code one

#include <stdio.h>
int main()
{
    for (;;)
    {
        printf("hehe\n");
    }
    return 0;
}

results of enforcement 👇

📝 Code two

#include <stdio.h>
int main()
{
    int x, y;
    for (x = 0, y = 0; x < 2 && y < 5; ++x, y++)
    {
        printf("hehe\n");
    }
    return 0;
}

results of enforcement 👇

🍑 3.3 do... while() loop

🍎 Syntax of do statement

do
 	Loop statement;
while(expression);

🍎 Execution process

🍎 Characteristics of do statement

The do... while() loop is compared with the while loop;
 
The do... while loop executes the loop statement once before judgment, so the loop executes at least once.
 
Because of the limited scenarios used, it is not often used.
 
Its nature is similar to that of a while loop, which will not be introduced here

📝 Code example

#include <stdio.h>

int main()
{
    int i = 10;
    do
    {
        printf("%d\n", i);
    } while (i < 10);
    
    return 0;
}

results of enforcement 👇

🍎 break and continue in do... while loop

Code one 📝

#include <stdio.h>

int main()
{
    int i = 10;
    do
    {
        if (5 == i)
            break;
        printf("%d\n", i);
    } while (i < 10);
    return 0;
}

results of enforcement 👇

Code two 📝

#include <stdio.h>

int main()
{
    int i = 10;
    do
    {
        if (5 == i)
            continue;
        printf("%d\n", i);
    } while (i < 10);
    
    return 0;
}

results of enforcement 👇

🍑 3.4 exercises

1. Write code to demonstrate that multiple characters move from both ends and converge to the middle.
 
2. Find a specific number n in an ordered array and print the subscript of the element.
 
3. Guess the numbers game.
 
You can think about these three questions! I'll explain it in the next article 😘

4. goto statement

C language provides goto statements that can be abused at will and labels that mark jump.
 
In theory, goto statement is not necessary. In practice, it is easy to write code without goto statement.
 
The most common usage 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.
 
In this case, using break will not achieve the goal. It can only exit from the innermost loop to the upper loop.

goto language is really suitable for the following scenarios:

for(...)
    for(...)
   {
        for(...)
       {
            if(disaster)
                goto error;
       }
   }
    ...
error:
 if(disaster)
         // Handling error conditions

The following is an example of using the goto statement, and then replacing the goto statement with a circular implementation

🍑 4.1 a shutdown procedure

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
    char input[10] = {0};
    system("shutdown -s -t 60");
    
again:
    printf("The computer will shut down within 1 minute. If you enter: do not shut down, cancel the shutdown!\n Please enter:>");
    scanf("%s", input);
    if(0 == strcmp(input, "Do not turn off"))
   	{
        system("shutdown -a");
   	}
    else
   	{
        goto again;
   	}
    return 0;
}

results of enforcement 👇

I won't demonstrate the execution results 🐶
 
system is the header file #include < stdlib h>;
 
shutdown -s -t 60 is the countdown of 1 minute, and the computer will shut down automatically;
 
strcmp compares the size of two strings;

shutdown -a is to cancel shutdown.

If you do not use goto statements, you can use loops:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char input[10] = {0};
    system("shutdown -s -t 60");
    while(1)
   {
        printf("The computer will shut down within 1 minute. If you enter: I am a pig, cancel the shutdown!\n Please enter:>");
        scanf("%s", input);
        if(0 == strcmp(input, "I'm a pig"))
       {
            system("shutdown -a");
            break;
       }
   }
    return 0;
}

ps: go trick your roommate 🤣

🌟 summary

🤗 The author's level is limited. If there is something wrong with the summary, please leave a message or private letter!
 
💕 If you think this article is good, then praise it 👍, comment 💬, Collection 🤞 Is my greatest support!
 
🌟 The more you know, the more you don't know. I'll see you next time!

Keywords: C Back-end

Added by signs on Thu, 06 Jan 2022 15:52:18 +0200