2 - branch and loop statements

Posted by radi8 on Wed, 17 Nov 2021 10:31:53 +0100

2 - branch and loop statements

1. Branch statement
if
switch

2. Circular statement
while
for
do while

3. goto statement (jump statement)

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 described later.
Control statements are used to control the execution flow of the program to realize various structural modes of the program. They are composed of specific statement definer. There are nine 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

What is the grammatical structure of the if statement?

Syntax structure:
//1 single branch
if(expression)
    sentence;
    
//2 two branches  
if(expression)
    Statement 1;
else
    Statement 2;

 //3 multi branch    
if(Expression 1)
    Statement 1;
else if(Expression 2)
    Statement 2;
else
    Statement 3;
#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");
   }
}

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.

If the condition holds, how should code blocks be used to execute multiple statements.
The pair {} here is a code block.

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

2.1.1 suspended else

Else matching: else matches the nearest if.

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

Use {}

//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 2 and code 4 are better, the logic is clearer and less error prone.

//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");  //Before the constant, prevent it from being written in the form of assignment num = 5
}

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

I didn't write if... else if... else if. The form of if is too complex, then we have to have different grammatical forms.
This is the switch statement// An expression can only be an integer and cannot represent a segment

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. For example:

#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:

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

So our code should be implemented as follows:

#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

If the expressed value does not match the value of all case tags, the structure is that all statements are skipped.
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, but it can appear anywhere in the statement list, and the statement flow will execute 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.

#include <stdio.h>
int main()
{
	int n = 1;
	int m = 2;
	switch (n)  // n=1
	{
	case 1:
		m++;  // m = 3
	case 2:
		n++; // n= 2
	case 3:
		switch (n) //n=2
		{//switch allows nested use
		case 1: // Do not execute
			n++; 
		case 2:
			m++; // m=4
			n++; // n=3
			break;  //Exit internal switch
		}
	case 4:
		m++;   // m = 5
		break;  //Exit external switch
	default:
		break;
	}
	printf("m = %d, n = %d\n", m, n);  // 5, 3
	return 0;
}

3. Circular statement

while
for
do while

3.1 while loop

Because we find that many practical examples in life are: we need to complete the same thing many times. How do we do it?
C language introduces us: while statement, which can realize loop.

//while syntax structure
while(expression)
 Circular statement;

For example, we implement:
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; }

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); // 1 2 3 4
	 i = i+1;
 }
 return 0; }

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.
So: break in while is used to permanently terminate the loop.

continue introduction

//continue code example 1
#include <stdio.h>
int main()
{
 	int i = 1;
	while(i<=10)
 {
	 if(i == 5)
		 continue;
	 printf("%d ", i);  // 1 2 3 4 6 7 8 9 10
	 i = i+1;
 }
 return 0; }
//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);  //2 3 4 6 7 8 9 10
 }
 return 0; }

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, it directly jumps to the judgment part of the while statement to judge the entry of the next cycle.

//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
//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, let's look at the syntax of the for loop:

3.2.1 syntax

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

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

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

3.2.2 break and continue in the for loop

//Code 1
#include <stdio.h>
int main()
{
 int i = 0;
 for(i=1; i<=10; i++)
 {
 if(i == 5)
 break;
 printf("%d ",i);  // 1 2 3 4
 }
 return 0; }
 
//Code 2
#include <stdio.h>
int main()
{
 int i = 0;
 for(i=1; i<=10; i++)
 {
 if(i == 5)
 continue;
 printf("%d ",i);  // 1 2 3 4 6 7 8 9 10
 }
 return 0; }

3.2.3 loop control variable of for statement

Recommendations:

  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 "closed before 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++)
{}

3.2.4 some variants of the for loop

#include <stdio.h>
int main()
{
 //Code 1
 for(;;)
 {
 printf("hehe\n");  // Dead cycle
 }
 
 //The initialization part, judgment part and adjustment part of the for loop can be omitted, but it is not recommended to omit them at the beginning of learning, which is easy to cause problems.
    
    //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");   // 10 * 10 = 100
       }
   }
    
    //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; }

One test question:

//How many times does the cycle take? 0
#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

3.3.1 syntax of do statement:

do
 Circular statement;
while(expression);

3.3.2 execution process

Title 3.3.3 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.4 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.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);
 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. How much do you want to know? I'll let you guess. How would you guess? Answer: you guess the middle number every time.

//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");
}
//If you implement a binary lookup function:
int bin_search(int arr[], int left, int right, int key) {
int mid = 0;
 while(left<=right)
 {
 	mid = (left+right)>>1;
 if(arr[mid]>key)
 {
 	right = mid-1;
 }
 else if(arr[mid] < key)
 {
 	left = mid+1;
 }
 else
 	return mid;  //Found, return subscript
 }
  return -1;  //can't find
}

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_ The max -- rand function can return the maximum value of a random number.
void game()
{
 int random_num = rand()%100+1;
 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));
 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.
In theory, goto statement is not necessary. In practice, it is easy to write code without goto statement.
However, goto statements are still useful in some situations. 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 not possible 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;
       }
   }
    ...
error:
 if(disaster)
         // Handling error conditions

Here is an example of using the goto statement, and then replacing the goto statement with a circular implementation: a shutdown program

#include <stdio.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: I am a pig, cancel the shutdown!\n Please enter:>");
    scanf("%s", input);
    if(0 == strcmp(input, "I'm a pig"))
   {
        system("shutdown -a");
   }
    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 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; }

Topics: C IDE Visual Studio Code