Elementary level of C language -- branch and loop statements

Posted by bhi0308 on Sun, 16 Jan 2022 12:23:58 +0100

In the last article, we had a preliminary understanding of the concept of C language. In the next series of articles in the beginning of C language, we will step closer to C language and see what tricks we can make. Just like learning to drive a motor vehicle, we already know what a car is, what parts it has, and some necessary traffic rules. Next, let's get on the bus together!

1. What is a statement?

Use a semicolon ";" in C language Separated is a statement, such as:

printf("hehe");
1 + 2;

2. Branch statement (select structure)

Life is full of choices. We are choosing when we divide subjects in high school, when we fill in volunteers in college, when we are a junior, we are choosing whether to find a job or take the postgraduate entrance examination. When we get an offer, we are still choosing which company to go to work. Are you still choosing?

2.1 if statement

What is an if statement? What is its grammatical structure?
Syntax structure 1:

if (expression)
 
      sentence;//Execute the statement when the expression conditions are met

Syntax structure 2:

if (expression) 
      Statement 1;//Statement 1 is executed when the expression is satisfied
else 
      Statement 2;//Expression execution statement 2 is not satisfied

Syntax structure 3:

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

Let's take a look at how to use the if statement through several examples:

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

Explain: if the result of the expression is true, the statement executes. How to express true and false in C language? We use 0 for false and non-0 for true.
According to the syntax, we can only execute one statement after the expression statement is judged. What should we do if we want to execute multiple statements? Here we should use code blocks. A pair of {} is a code block. Multiple statements can be placed in the code block.

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

2.1.1 suspended else
When you write this 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;
}
Correction:
//Proper use of {} can make the code logic 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;
}
//else matching; else matches the nearest if

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

//Code 3
int num = 1;
if (num == 5)
{
	printf("hehe\n");
}
//Code 4
int num = 1;
if (5 == num)
{
	printf("hehe\n");
}
//Obviously, code 2 and code 4 are better, the logic is clearer and less error prone.

2.1.3 if loop games
You must know the syntax of the if loop. Let's take a look at the following two topics.
1. Judge whether a number is odd

#include<stdio.h>
int main()//We enter an integer. When the number is odd, we print the odd number, and when the number is even, we print the even number
{
	int num = 0;
	printf("Please enter:>");
	scanf("%d", &num);
	//printf("\n");
	if (1 == num % 2)
	{
		printf("Odd number\n");
	}
	else
	{
		printf("even numbers");
	}
	return 0;
}


Have you learned? Let's look at the next question
2. Output an odd number between 1 and 100

#include<stdio.h>
int main()//Output odd numbers between 1 and 100
{
	int num = 1;
	for (num = 1; num <= 100;num++)//First generate numbers from 1 to 100
	{
		if (1 == num % 2)
		{
			printf("%d ", num);
		}
	}
	return 0;
}

2.2 switch branch statement

The switch syntax is very direct. It is used for multi branch situations, such as:
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
This is the switch statement. If we write the if branch statement, the form will be very complex
switch syntax:

switch (Integer expression)
{
	case Integer constant expression:
		sentence;//Executes when an integer constant expression is satisfied
}

Switch is like a switch. The integer expression in parentheses starts from the statement behind the integer constant expression after the corresponding case. When will it jump out? Or do you have to execute to the last statement? This requires us to use break to control.
2.2.1 break in switch statement
In the switch statement, we can't directly implement the branch. Only when combined with break can we realize the real branch, such as:

#include<stdio.h>
int main()
{
	int day = 0;
	scanf("%d",&day);// Enter an integer between 1 and 7
	switch (day)//Note that it must be an integer expression. Don't forget
	{
	case 1:
		printf("Monday\n");
		break;//If you encounter a break, you will jump out of the switch statement
	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;
}

If we change our requirements:
1. Enter a number between 1 and 5 to print "weekday".
2. Enter 6 or 7 to print "weekend".
In this way, our code should be implemented as follows:

#include<stdio.h>
int main()
{
	int day = 0;
	scanf("%d",&day);// Enter an integer between 1 and 7
	switch (day)//Note that it must be an integer expression. Don't forget
	{
	case 1:
	case 2:
	case 3:
	case 4:
	case 5:
		printf("weekday\n");
		break;
	case 6:
	case 7:
		printf("weekend\n");
		break;
	}
	return 0;
}

We can clearly feel that the actual effect of the break statement as the exit of the switch statement is to divide the statement list into different parts.
It is a good programming habit to add a break statement after the last case statement.
2.2.2 default clause
What if the value of the added expression does not match the value of all case tags? In fact, it's nothing. As a result, all statements are skipped. The program will not terminate or report an error. But what if we don't want to ignore the values of expressions that don't match all tags? Default can be used here. Write default 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. Putting a default statement in each switch statement is a good habit of programming. You can even add a break after it.

3. Circular statement

There are three types of loop statements: while loop, for loop and do while loop.

Life is like this. Paying day after day will eventually pay back, as long as you stick to it. Of course, you must stick to it. You can't turn life into a dead cycle, don't you think?

3.1 while loop

We have mastered the if statement:

 if(condition) 
      sentence;

When the conditions are met, the statement after the if statement will be executed, otherwise it will not be executed, but this statement will only be executed once. If the same thing needs to be completed many times, what should we do? The while statement is introduced into C language, which can realize the loop.

//while syntax structure 

  while(expression)
      Loop statement;

Process executed by while statement:

We can print 1 ~ 10 numbers 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
Now that we know the basic syntax of the while statement, let's learn how to use 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;
}//The result of the code output is 1 2 3 4

Summary:
The role of break in the loop: as long as a break is encountered in the loop, all subsequent loops will be stopped. Therefore, the break in while is used to permanently stop the loop.
continue introduction

//Code 1
#include<stdio.h>
int main()
{
	int i = 1;
	while (i <= 10)
	{
		if (i == 5)
			continue;
		printf("%d ", i);
		i = i + 1;
	}
	return 0;
}//The result of the code output is 1 2 3 4. However, the program does not mean to terminate because it enters an endless loop
//Code 2
#include<stdio.h>
int main()
{
	int i = 1;
	while (i <= 10)
	{
		i = i + 1;
		if (i == 5)
			continue;
		printf("%d ", i);
	}
	return 0;
}//The result of the code output is 2 3 4 5 6 7 8 9 10

Summary: the function of continue in the while loop is to terminate this loop, that is, the code behind continue in this loop will not be executed again, but directly jump to the judgment part of the while statement to judge the entry of the next loop. Let's look at the following codes:

//What does code mean?
//Code 1
#include<stdio.h>
int main()
{
	int ch = 0;
	while ((ch = getchar()) != EOF)//getchar(): read the input characters
		putchar(ch);//putchar(): output the read characters
	return 0;
}

3.2 for loop

Now that we know the while loop, let's look at the for loop.
3.2.1 for loop syntax

for(Expression 1;Expression 2;Expression 3) 	
    Circular statement;
    
Expression 1:The initialization part is used to initialize the loop variable
 Expression 2:The condition judgment part is used to judge when the cycle ends
 Expression 3:The adjustment part is used for the adjustment of cyclic variables

Practical application: use the for loop to print 1 ~ 10 numbers on the screen

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

Execution flow chart of for loop:

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

int i = 0;//Initialization part
while (i <= 10)//Judgment part
{
	printf("hehe\n");
	i = i + 1;//Adjustment part
}

//Use the for loop to achieve the same function
for (i = 1; i <= 10; i++)
{
	printf("hehe\n");
}//The code looks cleaner

It can be found that there are still three necessary conditions for the for loop in the while loop, but the three parts may deviate far due to the problem of code style, so the search and modification are not direct and convenient. Therefore, the style of for loop is better, and the frequency of use of for loop is the highest.
3.2.2 break and continue in for loop
break and continue have the same meaning in the for loop as in the while loop, but there are still some differences. You can find the differences by carefully observing the codes at the following two ends:

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 print result is 1 2 3 4
 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 print result is 1 2 3 4 6 7 8 9 10

3.2.3 loop control variable of for statement
some suggestions:
1. Do not modify the loop variable in the 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 "open before close interval":

  int i = 0;
  for(i = 0;i < 10;i++)

3.2.4 some variants of the for loop

#include<stdio.h>
int main()
{
	//Variant 1
	for (; ; )
	{
		printf("hehe\n");
	}//Infinite loop printing hehe
	//Variant 2
	int x, y;
	for (x = 0, y = 0; x < 2 && y < 5; x, y++)
	{
		printf("hehe\n");//Print twice hehe
	}
	return 0;
}

3.2.5 one pen test question
How many times does the following code cycle?

#include<stdio.h>
int main()
{
	int i = 0;
	int k = 0;
	for (i = 0, k = 0; k = 0; i++, k++)
		k++;
	return 0;
}//The result is 0 executions

This problem seems simple. There are only a few lines of code, but at this time, we often need to pay attention to: the problem is often hidden in the details we ignore. Carefully observe the judgment statement in the for loop: k = 0; This is an assignment statement. In the computer, 0 represents false, which means that the judgment condition is always false and loops once. Similarly, numbers other than 0 represent truth. To facilitate our observation, I change the code to the following form:

#include<stdio.h>
int main()
{
	int i = 0;
	int k = 0;
	for (i = 0, k = 0; k = 2; i++, k++)
		printf("hehe ");//Dead cycle printing hehe
	return 0;
}//Full screen hehe, do you see it?

3.3 do ··· while() cycle

Let's introduce the third loop: the do ··· while() loop. What's unusual about it?
3.3.1 syntax of do ··· while statement

do 
     Loop statement;
while(expression);

3.3.2 execution process

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;
}//The program is executed only once and prints 10

3.3.4 break and continue in do ··· while loop

#include<stdio.h>
int main()
{
	int i = 10;
	do
	{
		if (5 == i)
			break;//The execution will jump out of the loop
		printf("%d\n", i);
	} while (i < 10);
 	//Print 1 2 3 4 
	return 0;
}
#include<stdio.h>
int main()
{
	int i = 1;
	do
	{
		if (5 == i)
			continue;//The program will skip the following code and execute from scratch
		printf("%d\n", i);
		i++;
	} while (i < 10);
	//Print 1 2 3 4, and then the program enters the dead cycle
	return 0;
}

3.4 circular games

3.4.1 half search: one day I bought a pair of Nike. You asked me how much it was, and I said it was no more than 500 You are still curious. If you want to know how much it is, I will let you guess. Every time I guess, I will give corresponding tips to tell you whether it is big or small. How will you guess?
answer; You guess the middle number every time.
Code implementation:

#include<stdio.h>
int main()
{
	int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
	int left = 0;//Array subscripts start at zero
	int right = sizeof(arr) / sizeof(arr[0]) - 1;//The index of the last element of the array
	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("Found it\n");
	else
		printf("can't find\n");
	return 0;
}

3.4.2 number guessing game
I asked the computer to randomly generate a number within a certain range. You guess. Each time you guess, the computer will give corresponding prompts. You continue to guess according to the prompts until you get it right.
Code implementation:

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void menu()
{
	printf("********************************");
	printf("***********1 . play*************");
	printf("***********0 . exit*************");
	printf("********************************");
}
void game()
{
	int random_num = rand() % 100 + 1;//In this way, a number of 0 ~ 100 can be generated
	int input = 0;
	while (1)
	{
		printf("please enter a number:>");
		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));
	//If you are interested, you can understand the concept of timestamp. Here we use timestamp to generate 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);//As long as the input is not 0, it will not jump out
	return 0;
}

4.goto statement

C language provides goto statements that can be abused at will and labels that mark jump, but goto statements are not necessary in theory. In practice, it is easy to write code without goto statements. But in some cases, goto statements are still used. The most common usage is to terminate the processing process of the program in some deeply nested structures, such as jumping out of two or more layers of loops at a time. In this case, the purpose of using break is not achieved. Break can only jump out of one layer of loop at a time.
Here is an example of using the goto statement: a shutdown program

#include<stdio.h>
int main()
{
	char input[10] = { 0 };
	system("shutdown -s -t 60");
again:
	printf("The computer will be at 60 s Internal shutdown. If you enter that 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 you do not use the goto statement, you can use a loop:
#include<stdio.h>
#include<stdlib.h>
int main()
{
	char input = { 0 };
	system(shutdown - s - t 60);
	while (1)
	{
		printf("The computer will be at 60 s Internal shutdown. If you enter that 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;
}

The goto statement is really applicable to the following scenarios:

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

Well, that's all about branches and loops. Let's learn about functions in the next article.

Topics: C Back-end