C language series - Section 2 - branch and loop statements

Posted by vbcoach on Sat, 12 Feb 2022 13:42:41 +0100

1. Branch statement
if
switch
2. Circular statement
while
for
do while
3.goto statement

What is a statement?

C statements can be divided into the following five categories:

  1. Expression statement
  2. Function call statement
  3. Control statement (introduced in this chapter)
  4. Compound statement
  5. Empty statement

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. There are nine kinds of control statements in C language.

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)

2.1 if statement

Syntax structure of if statement

Syntax structure:
/*First kind*/
	if(expression)
	{
    sentence;
	}
/*Second*/
	if(expression)
	{
    Statement 1;
	}
	else
	{
    Statement 2;
	}
/*Third*//*Multi branch*/    
if(Expression 1)
    Statement 1;
else if(Expression 2)
    Statement 2;
else
    Statement 3;

The practice is as follows:

#include <stdio.h>
//Code 1
int main()
{
 int age = 0;
    scanf("%d", &age);
    if(age<18)
   {
        printf("under age\n");
   }
}
//Code 2
#include <stdio.h>
int main()
{
 int age = 0;
    scanf("%d", &age);
    if(age<18)
   {
        printf("under age\n");
   }
    else
   {
        printf("adult\n");
   }
}
//Code 3
#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");
   }
}

Add: how to express true and false in C language?

0 means false and non-0 means true.

2.1.1 suspended else

Else matching: else matches the nearest if.
The conflict code is as follows:

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

reflection:
Which if does the above else match?
answer:
It matches the second if, but it is not easy to see when there are too many codes. Therefore, the following provisions are made:

//Proper use of {} can make the logic of the code clearer.
//Code style is important
#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.1.2 comparison of if writing forms

//Code 1
if (condition) {
    return x;
}
return y;
//Code 2
if (condition)
{
    return x;
}
else
{
    return y;
}
//The position of curly braces obtained by comparing 1 and 2 should correspond up and down, and the code is clear


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

/*3,4 The comparison shows that if the judgment statement appears and is equal to a number, the number should be in
 front*/
The reason is: in code 3, if you accidentally put num==5,finish writing sth. num=5 Then the judgment statement will also
 Pass. as a result of if When making a judgment, the judgment is*Whether the expression in parentheses is true.

num = 5 Assignment expression, the overall value is the assignment value 5, (unless the assignment value is 0, if Not established
 The rest will be established) and if Whether established or not, num The value of will change to the value assigned

num == 5 Judgment expression, only 0 and 1, num If the value is equal to 5, then the value of this expression
 Which is equal to 1, num If it is not equal to 5, then the value of this expression is 0.(also if Regardless of success
 Whether it is established or not, num (the value of does not change)

2.1.3 practice

  1. Judge whether a number is odd
  2. Output odd number between 1-100
Question 1:
#include<stdio.h>
int main()
{
	int n;
	scanf("%d", &n);
	if (n % 2 == 1)
	{
		printf("%d It's an odd number\n", n);
	}
	else
	{
		printf("%d Not odd\n", n);
	}

	return 0;
	
}
Question 2:
#include<stdio.h>
	int main()
	{
		/*Method 1*/
		int i;
		for (i = 1; i <= 100; i++) //Traverse all numbers between 1-100
		{
			if (i % 2 == 1) //Judge whether it is an odd number
			{
				printf("%d ", i);//If it is an odd number, output it. Don't forget to have a space between each number
			}
		}
		return 0
	
	/*Method 2*/
		int i;
			for (i = 1; i <= 100; i = i + 2)//Directly traverse odd numbers between 1-100
			{
				printf("%d ", i); //Just output directly. Don't forget to have a space between each number
			}
	}

2.2 switch statement

The switch statement is also a branch statement.
It 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 it is written as if... else if... else if, you can try it, but the switch statement is better, as follows:

Switch (integer expression){
Statement item;
}

What are statement items?

//Are some case statements:
//As follows:
case integer constant expression:
sentence;

2.2.1 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

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

Sometimes our needs change: (break application)

  1. Input 1-5 and output "weekday";
  2. Input 6-7 and output "weekend"
#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; }

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

Good programming habits

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.).

2.2.2 default clause

What if the expressed value does not match the value 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.
What if you don't want to ignore all the values of the expression when it doesn't match?
You can add a default clause to the statement list and put the following tag
default:
Write where any case tag 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.

2.2.3 exercise (the fifth general example of C language)

#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);//The output is m = 5, n = 3
    return 0;
}

3. Circular statement

3.1 while cycle

We have mastered the if statement:

if(condition)
     sentence;

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.
Because 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)
 Circular statement;

For example, we realize:

Print numbers 1-10 on the screen.

#include <stdio.h>
int main()
{
	int i = 1;
	while(i<=10)
	{
	printf("%d ", i);
	i = i+1;
	}
	return 0;
}

The above code has helped me understand the basic syntax of the while statement. Let's learn more:

3.1.1 break and continue in while statement

break introduction

//break code instance
#include <stdio.h>
int main()
{
	int i = 1;
	while (i <= 10)
	{
		if (i == 5)
			break;
		printf("%d ", i);
		i = i + 1;
	}
	return 0;
}

What is the result of the code output here?

1 2 3 4
1 2 3 4 5
1 2 3 4 5 6 7 8 9 10
1 2 3 4 6 7 8 9 10

Summary:

The role of break in the while loop:
In fact, as long as you encounter a break in the cycle, stop all the later cycles and directly terminate the cycle.
So: break in while is used to permanently terminate the loop. (if you encounter a break corresponding to this while in while, you can jump out of this while directly)

continue introduction

//continue code example 1
#include <stdio.h>
int main()
{
	int i = 1;
	while (i <= 10)
	{
		if (i == 5)
			continue;
		printf("%d ", i);
		i = i + 1;
	}
	return 0;
}

What is the result of the code output here?

1 2 3 4
1 2 3 4 5
1 2 3 4 5 6 7 8 9 10
1 2 3 4 6 7 8 9 10

//continue code example 2
#include <stdio.h>
int main()
{
    int i = 1;
    while (i <= 10)
    {
        i = i + 1;
        if (i == 5)
            continue;
        printf("%d ", i);
    }
    return 0;
}

What is the result of the code output here?

1 2 3 4
1 2 3 4 5
1 2 3 4 5 6 7 8 9 10
1 2 3 4 6 7 8 9 10
2 3 4 6 7 8 9 10

Summary:
The function of continue in the while loop is:
Continue is used to terminate this cycle, that is, the code behind continue in this cycle will not be executed,
Instead, jump directly to the judgment part of the while statement. Determine the inlet of the next cycle

Look at a few more codes:

//What does code mean?
//Code 1
#include <stdio.h>
int main()
{
    int ch = 0;
    while ((ch = getchar()) != EOF)
        putchar(ch);
    return 0;
}
//The code here can be used to clean up the buffer with appropriate modifications Self Baidu, buffer

/*1.EOF Equal to - 1, getchar is equal to the function of scanf. When gerchar can read data
 The return value of the ch = gerchar() expression is 1. But when the value is not read,
The return value is - 1.*/

/*So use while ((CH = getchar())= EOF)
Function: continuously read in data. When no data is read in, the cycle stops
 You can also use while (scanf) ('% d', & CH)= EOF)
*/

//Code 2
#include <stdio.h>
int main()
{
    char ch = '\0';
    while ((ch = getchar()) != EOF)
    {
        if (ch < '0' || ch > '9')
            continue;
        putchar(ch);
    }
    return 0;
}
//The function of this code is to print only numeric characters and skip other characters

3.2 for loop

We already know the while loop, but why do we need a for loop?
First look at the syntax of the for loop:

3.2.1 grammar

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

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

Practical problems:

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

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 while
for (i = 1; i <= 10; i++) {
	printf("hehe\n");
}

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

3.2.2 break and continue in for loop

break and continue can also appear in the for loop, and their meaning is the same as that in the while loop.
But there are some differences:

//Code 1
#include <stdio.h>
int main()
{
	int i = 0;
	for (i = 1; i <= 10; i++)
	{
		if (i == 5)
			break;
		printf("%d ", i);
	}
	return 0;
}
/*The final output is 1 2 3 4 It ends when there is a break in the surface*/

//Code 2
#include <stdio.h>
int main()
{
	int i = 0;
	for (i = 1; i <= 10; i++)
	{
		if (i == 5)
			continue;
		printf("%d ", i);
	}
	return 0;
}
/*The output is 1 2 3 4 6 7 8 9 10
 On the surface, if you encounter continue in for, you will directly cycle again and do not continue to go down, but I + + (i.e
 For each for loop, the adjustment statement will be executed after continue)
*/

3.2.3 loop control variable of for statement

Recommendations:

  1. Do not modify the loop variable 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 as "closed before open interval".
int i = 0;
//The writing method of front closing and back opening
for(i=0; i<10; i++)
{}
//Both sides are closed intervals
for(i=0; i<=9; i++)
{}
The advantage of front closing and back opening is that you can directly see the number of cycles 10-0=10

3.2.4 some variants of the for loop

#include <stdio.h>
int main()
{
 //Code 1
 for(;;)
 {
 printf("hehe\n");
 }
    //The initialization part, judgment part and adjustment part of the for loop can be omitted, but
    //It is not recommended to omit at the beginning of learning, which is easy to lead to questions
 Question.
    
    //Code 2
    int i = 0;
    int j = 0;
    //How many hehe are printed here?
    for(i=0; i<10; i++)
   {
        for(j=0; j<10; j++)
       {
 printf("hehe\n");
       }
   }
    
    //Code 3
    int i = 0;
    int j = 0;
    //If the initialization part is omitted, how many hehe are printed here?
    for(; i<10; i++)
   {
        for(; j<10; j++)
       {
 printf("hehe\n");
       }
   }
    
 //Code 4 - use more than one variable to control the loop
 int x, y;
    for (x = 0, y = 0; x<2 && y<5; ++x, y++)
   {
        printf("hehe\n");
   }
 return 0; }

3.2.5 one pen test question (the sixth general example of C language)

//How many times does the cycle take?
#include <stdio.h>
int main()
{
	int i = 0;
	int k = 0;
	for (i = 0, k = 0; k = 0; i++, k++)
		k++;
	return 0;
}

3.3 do... while() loop (just understand, not commonly used)

3.3.1 syntax of do statement

do
 Circular statement;
while(expression);/*Note that there is a semicolon after while*/

3.3.2 characteristics of do statement

The loop is executed at least once. The scenarios used are limited, so it is not often used

#include <stdio.h>
int main()
{
	int i = 10;
	do
	{
		printf("%d\n", i);
	} while (i < 10);
	return 0;
}

3.3.3 break and continue in do while loop

#include <stdio.h>
int main()
{
	int i = 10;

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

	return 0;
}
#include <stdio.h>
int main()
{
	int i = 10;

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

	return 0;
}

3.4 practice

  1. Calculate the factorial of n.
  2. Calculate 1+ 2!+ 3!+……+ 10!
  3. Find a specific number n in an ordered array. (explain binary search)
  4. Write code to demonstrate that multiple characters move from both ends and converge to the middle.
  5. Write code to simulate the user login scenario, and can only log in three times. (it is only allowed to enter the password three times. If the password is correct
    Prompt to log in. If the input is wrong three times, exit the program.

3.4.1 exercise reference code

//Code 1
//Write code to demonstrate that multiple characters move from both ends and converge to the middle
#include <stdio.h>
int main()
{
    char arr1[] = "welcome to bit...";
    char arr2[] = "#################";
    int left = 0;
    int right = strlen(arr1) - 1;
    printf("%s\n", arr2);
    //while loop implementation
    while (left <= right)
    {
        Sleep(1000);//Just understand, please Baidu
        arr2[left] = arr1[left];
        arr2[right] = arr1[right];
        left++;
        right--;
        printf("%s\n", arr2);
    }
    //for loop implementation
    for (left = 0, right = strlen(src) - 1;
        left <= right;
        left++, right--)
    {
        Sleep(1000);
        arr2[left] = arr1[left];
        arr2[right] = arr1[right];
        printf("%s\n", target);
    }
    retutn 0;
}
//Code 2
int main()
{
    char psw[10] = "";
    int i = 0;
    int j = 0;
    for (i = 0; i < 3; ++i)
    {
        printf("please input:");
        scanf("%s", psw);
        if (strcmp(psw, "password") == 0)
            break;
    }
    if (i == 3)
        printf("exit\n");
    else
        printf("log in\n");
}

3.4.2 half search algorithm

For example, when I bought a pair of shoes, you asked me how much it was, and I said no more than 300 yuan. You're still curious. If you want to know how much, I'll let you know
Guess, what would you guess?
Answer: you guess the middle number every time.
Code implementation:

Implemented in the main function:
int main()
{
	int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
	int left = 0;
	int right = sizeof(arr) / sizeof(arr[0]) - 1;
	int key = 7;
	int mid = 0;
	while (left <= right)
	{
		mid = (left + right) / 2;
		if (arr[mid] > key)
		{
			right = mid - 1;
		}
		else if (arr[mid] < key)
		{
			left = mid + 1;
		}
		else
			break;
	}
	if (left <= right)
		printf("eureka,The subscript is%d\n", mid);
	else
		printf("can't find\n");
}

3.4.3 realization of guessing numbers game

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void menu()
{
	printf("**********************************\n");
	printf("*********** 1.play     **********\n");
	printf("*********** 0.exit     **********\n");
	printf("**********************************\n");
}
//RAND_MAX--rand function can return the maximum value of random number.
void game()
{
	int random_num = rand() % 100 + 1; //Generate random number
	int input = 0;
	while (1)
	{
		printf("Please enter the number you want to guess>:");
		scanf("%d", &input);
		if (input > random_num)
		{
			printf("Guess big\n");
		}
		else if (input < random_num)
		{
			printf("Guess it's small\n");
		}
		else
		{
			printf("Congratulations, you guessed right\n");
			break;
		}
	}
}
int main()
{
	int input = 0;
	srand((unsigned)time(NULL)); //This must be written when generating random numbers
	do
	{
		menu();
		printf("Please select>:");
		scanf("%d", &input);
		switch (input)
		{
		case 1:
			game();
			break;
		case 0:
			break;
		default:
			printf("Selection error,Please re-enter!\n");
			break;
		}
	} while (input);
	return 0;
}

4. goto statement

C language provides goto statements that can be abused at will and labels that mark jump.
Theoretically, goto statement is not necessary. In practice, it is easy to write code without goto statement.
But in some cases, goto statement is still useful. The most common usage is to terminate the processing process of the program's deeply nested structure.
For example: jump out of two or more layers of loops at a time.
In the case of multi-layer loops, it is impossible to use break. 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;//Jump out of multiple loops and use goto
       }
   }
    ...
error:

The following is an example of using goto statement, and then replacing goto statement with loop implementation:

A shutdown program

#include <stdio.h>
int main()
{
	char input[10] = { 0 };
	system("shutdown -s -t 60");//Countdown shutdown code
again:
	printf("The computer will shut down within 1 minute. If you enter: I'm a pig, cancel the shutdown!\n Please enter:>");
	scanf("%s", input);
	if (0 == strcmp(input, "I'm a pig"))
	{
		system("shutdown -a"); //Shutdown cancellation code
	}
	else
	{
		goto again;
	}
	return 0;
}

If the goto statement is not applicable, you can use a loop:

#include <stdio.h>
#include <stdlib.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'm 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; }

About the extension of shutdown command - (please click here)
This chapter ends.

Topics: C Back-end