# Branch statements and loop statements (detailed explanation + code demonstration + illustration) catalogue

preface

1, What is a statement?

2, Branch statement (select structure)

1.if statement

Grammatical structure

Wrong writing

Suspended else problem

Comparison of if writing forms

2.switch statement

Grammatical structure

What is a statement item?

break in switch statement

default clause

Exercises

3, Circular statement

1.while statement

Grammatical structure

Execution process

continue in a while statement

break in while statement

case analysis

2.for statement

Grammatical structure

Execution process

continue in for statement

break in the for statement

Loop control variable of for statement

Some variants of the for loop

Written test questions

3. do... while loop

Grammatical structure

Execution process

break in do... while statement

continue in do... while statement

4, goto statement

1. Recommendations

2. Really suitable scenario

5, Search of integer ordered array

1. Traversal method

2. Half / dichotomy

# preface

Through this blog, we will introduce branch statements and loop statements in detail

We need to know that C language is a structured programming language. What does structure mean here? Usually, when we write a C program, we will write three structures:

• Sequential structure
• Cyclic structure
• Select structure   Computer language highly abstracts the things in our life. Through a computer language, we can express the problems in our life, so as to help us solve the problems in our life conveniently.

•   Branch statement

if
switch

• Circular statement

while
for
do while

•   goto Statement

# 1, What is a statement?

A semicolon in C language;   Separated is a statement, as follows:

```int main()
{
28;
int a = 5;
;          //Empty statement
return 0;
}```

# 2, Branch statement (select structure) How does choice structure C describe it?

## 1.if statement

### Grammatical structure

```//1.
if (expression)
sentence;

//2.
if (expression)
Statement 1;
else
Statement 2;

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

Experience it with the following code:

Code 1

```int main()
{
int age = 8;
if (age < 18)
{
printf("juveniles\n");
}
return 0;
}```

The if statement here will judge the expression in the parentheses. If the expression is true, the statement will be executed, and if the expression is false, it will not be executed. Here age < 18 is obviously true, so the statement is executed.

Operation results: Code 2

```int main()
{
int age = 28;
if (age < 18)
{
printf("juveniles\n");
}
else
{
}
return 0;
}```

The condition behind the if statement here is false, so the statement after if is not executed, but the statement after else is executed

Operation results: Code 3

```int main()
{
int age = 35;
if (age < 16)
{
printf("juvenile\n");     //Statement 1
}
else if (age <= 30)
{
printf("youth\n");     //Statement 2
}
else if (age <= 50)
{
printf("middle age\n");      //Statement 3
}
else     //This last else can also be omitted
{
printf("old age\n");      //Statement 4
}
return 0;
}```

Operation results: The if in this code is multi branched. First, judge the condition that age < 16 is not tenable, so do not execute statement 1, then judge whether age is between 16 and 30 or not, do not execute statement 2, and then judge whether age is between 30 and 50, so sentence 3 is executed here, and the following statements are no longer executed.

### Wrong writing

1. The judgment conditions in the if statement are in the form of continuous comparison   eg.if(16  <= Age < = 30), which is actually different from what we want to express. The meaning of the judgment condition here is to first judge whether 16 < = age is true and find it is true, so the condition is true, and then judge whether 1 < = 30 is true, find it is true and execute the corresponding statement
2. Note that if you want to execute multiple statements at the same time when the condition is true or false in the if statement, it should be enclosed in curly brackets, as follows:

Incorrect writing:

```#include <stdio.h>
int main()
{
int age = 15;
if (age < 18)
printf("juveniles\n");
printf("Be obedient\n");
else
return 0;
}```

Correct writing:

```#include <stdio.h>
int main()
{
int age = 15;
if (age < 18)
{
printf("juveniles\n");
printf("Be obedient\n");
}                          //When multiple statements are executed at the same time, curly braces should be used
else
{
}
return 0;
}```

Operation results: One more word, it means true or false in C language

0 ----------------- false

Non 0 ------- true

### Suspended else problem

First, look at the following code and think about the result of the program?

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

The result is hello?     goodbye?   Or         Let's verify it The result is nothing. Why?

Note that there is an else and two if in this code. Else matches the nearest if, that is, if(b==2),   Then, this pair of if... Else as a whole is equivalent to the execution statement when the condition of the first if(a==1) is true, and a==1 is false, so the latter pair of if... Else will not be executed and directly come to return 0, so the operation result is nothing

This code itself is also a pit. Deliberately aligning else with the first if makes us mistakenly think that they do match. Therefore, when we write code, we must pay attention to indenting the code that should be indented. Do not indent the code that should not be indented at will, and do not omit curly braces at will

After correction (there can also be other modification methods to see what you want to achieve):

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

### Comparison of if writing forms

Code 1:

```if (condition)
{
return x;
}
return y;```

The function of this code is to return x if the condition is true and y if the condition is not true. But here we may intuitively see that the first feeling is that it is not such a function and is easy to be misunderstood. This is a bad code style Code 2:

```if(condition)
{
return x;
}
else
{
return y;
}```

This code is much better than code 1. You can see what it wants to do at a glance. It is very important to know the code style

Code 3:

```#include <stdio.h>
int main()
{
int a = 5;
if (a = 8)   //bug
{
printf("hello");
}
return 0;
}```

Originally, I wanted to judge whether it was equal to 8, but when I wrote it, I assigned 8 to a. in this way, the judgment condition becomes the eternal condition, and the program can run successfully. It is not easy to find bugs in the later stage. Many people make such mistakes, and it is not easy to find bugs

This can be effectively avoided by the following code

```#include <stdio.h>
int main()
{
int a = 5;
if (8 == a)     //Write 8 first
{
printf("hello");
}
return 0;
}```

In this way, if your code is written incorrectly as 8=a, the compiler will report an error and the bug is easy to find

```#include <stdio.h>
int main()
{
int a = 5;
if (8 = a)
{
printf("hello");
}
return 0;
}``` The code can't run directly, and the errors are displayed directly, which will make it easier to correct the errors

## 2.switch statement

switch statements are mainly used in the case of multiple branches. if... else is too cumbersome in the case of multiple branches.

eg.

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 7

### Grammatical structure

```switch(Integer expression)
{
Statement item;
}```

First, experience it through the following code:

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

Operation results Now we find that we originally wanted to input 2 and then let it output Tuesday, but the result was from Tuesday to Sunday. Why? This is mainly because we ignored the termination of the switch statement. We should add break to jump out of the switch and make the following modifications:

```#dinclude <stdio.h>
int main()
{
int day = 0;
scanf("%d", &day);
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;
}``` So it only executes the statements after case 2

Note:

1. The parenthesis after switch must be an integer expression
2. Each case is a statement item
3. case must be followed by a constant expression, and variables cannot appear
4. If there is no break in the switch statement, it will be executed from where it goes in. Therefore, when using the switch statement, pay attention to add break where the code jumps out

### What is a statement item?

Statement items are case statements: eg

```case integral 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

Now, if we want to output working days when we input numbers between 1-5 and rest days when we input numbers between 6-7, we can implement it, as follows:

```#include <stdio.h>
int main()
{
int day = 0;
scanf("%d", &day);
switch (day)
{
case 1:
printf("weekdays\n");
break;
case 2:
printf("weekdays\n");
break;
case 3:
printf("weekdays\n");
break;
case 4:
printf("weekdays\n");
break;
case 5:
printf("weekdays\n");
break;
case 6:
printf("Rest Day\n");
break;
case 7:
printf("Rest Day\n");
break;
}
return 0;
}```

However, it will be troublesome to do so. The same statement is executed from case 1 to case 5. In fact, we can simplify the code in this way

```#include <stdio.h>
int main()
{
int day = 0;
scanf("%d", &day);
switch (day)
{
case 1:
case 2:
case 3:
case 4:
case 5:
printf("weekdays\n");
break;
case 6:
case 7:
printf("Rest Day\n");
break;
}
return 0;
}```

Operation results: This is equivalent to dividing the code into blocks. One block executes the same case. From here, we can understand that the actual effect of the break statement is to divide the statement list into different parts

reminder:

1. It is also recommended to add break after the last case statement
2. The switch statement supports qi

### default clause

In the switch statement, you can execute the corresponding case statement according to the value of the following integer expression. What if the value of the integer expression does not have a corresponding case statement? The program will not terminate or report an error, because this situation is not considered an error in C, but it is recommended to add default or break after break, which is better

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.

The default statement can be placed anywhere in the switch statement if it is logical

The following code:

```#include <stdio.h>
int main()
{
int a = 0;
scanf("%d", &a);
switch (a)
{
case 1:
printf("666\n");
break;
case 2:
printf("233333\n");
break;
default:
printf("Input error\n");
break;
}
return 0;
}``` ### Exercises

```#include <stdio.h>
int main()
{
int n = 1;
int m = 2;
switch (n)
{
case 1:
m++;
case 2:
n++;
case 3:
switch (n)
{
case 1:
n++;
case 2:
m++;
n++;
break;
}
case 4:
m++;
break;
default:
break;
}
printf("m = %d, n = %d\n", m, n);
return 0;
}```

What is the output of this question?

analysis:

First, n is 1. After entering the switch statement, it starts to execute from case1. There is no break behind case1 and case2, so it is always executed. After executing case1 and case2, m==3,n==2, and then enter case3. The switch is nested here. The switch inside starts to execute from case2, m==4,n==3. After encountering a break, it jumps out of the nested break, and then executes Case4, M = = 5 of the outer switch statement, N = = 3, and then come out of the switch to print the results

Operation results: # 3, Circular statement

• while
• for
• do...while

The same thing is executed repeatedly. In C language, circular statements are used

## 1.while statement

### Grammatical structure

```while(expression)
Loop statement;```

### Execution process What if we want to print numbers 1-10 here?

The code is as follows:

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

Code analysis:

1. Here, in the brackets after while is the judgment condition for loop termination. If the condition is true, continue the loop; If the condition is false, terminate the cycle
2. i + + is an accumulator, which is used to change the value of i. each cycle, i plus 1, and the value of i will be printed

Operation results: ### continue in a while statement

```#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 running after adding continue? analysis:

The if statement here is used for judgment. When i==5, the continue statement is executed,

The function of continue is to skip this cycle and continue the next cycle

In this code, that is, when i==5, skip this loop and do not execute the following printf and i + +;

After printing 1 2 3 4, it does not stop, but enters the dead cycle

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

### break in while statement

Or look at the code:

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

What happens after changing the original continue to break? Program output 1 2 3 4

Analysis: when it is equal to 5, the break under the if statement is executed; This directly jumps out of the while 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. So: in while
break is used to permanently terminate a loop.

Here, continue and break have the following flow charts to help understand ### case analysis

Code 1:

```#include <stdio.h>
int main()
{
int ch = 0;
while ((ch = getchar()) != EOF)
putchar(ch);
return 0;
}```

explain:

getchar() obtains a character from the keyboard. Looking up the document, you will see that the form of getchar function is int getchar (void); The return value is an integer (in fact, it returns the ASCII code value of the obtained character)

putchar() prints a character to the screen

EOF(end of file) is the end flag of the file. The essential value is - 1

Here, the judgment condition after the while statement means to obtain a character from the keyboard. If the character is not EOF, execute the following loop body (print the obtained character). And as long as it is not EOF, the program can always read and print.

Operation results: Note: why does the loop not stop when EOF is entered here?

This is because inputting EOF is equivalent to the program reading the three letters of EOF and printing them respectively

To terminate the loop if the loop condition is false, you should press Ctrl + Z on the keyboard, and getchar () will get EOF from the keyboard

Code 2:

```#include <stdio.h>
int main()
{
int ch = 0;
ch = getchar();
if ('Y' == ch)
{
printf("Confirmation successful\n");
}
else
{
printf("Waiver of confirmation\n");
}
return 0;
}```

result: explain:

After pressing Ctrl+F5, my operation: press enter after entering 123 on the keyboard, and then it becomes the situation shown in the above figure. Before I enter Y/S, I have automatically displayed abandonment confirmation. What is this situation?

You know: scanf and getchar are used for input, and where do we input them?   Of course, it's input from the keyboard, but scanf or getchar don't take things directly from the keyboard.

There is an input buffer between the input function and the keyboard. When we enter the password, enter 123, and then press the Enter key (equivalent to '\ n') in order to enter the password, and then the password will be written in. Then scanf will take data from the input buffer, which will only take 123, but '\ n' will not be taken away. Next, when running getchar, getchar finds that there is something else in the input buffer, and then getchar will take '\ n', so we have no chance to input data into getchar

As shown in the figure below: Solution: after scanf takes the password from the input buffer, we can find a way to take this' \ n 'too, and remove the' \ n 'before getchar() is executed

```#include <stdio.h>
int main()
{
int ch = 0;
getchar();
ch = getchar();
if ('Y' == ch)
{
printf("Confirmation successful\n");
}
else
{
printf("Waiver of confirmation\n");
}
return 0;
}```

result: Use getchar() to empty the input buffer

If I want to empty the input buffer, I can use getchar(), as follows:

```while (getchar() != '\n')
{
;
}```

## 2.for statement

Through our usual practice, we can also find that among the three loop statements, for is the most used, while is the second, and do... While is the least

First look at the following code for the while loop

```#include　<stdio.h>
int main()
{
int a = 0;      //Initialization part
while (a < 10)    //Judgment part
{
printf("%d ", a);
}
return 0;
}```

In fact, if we look at this code carefully, we will find that the initialization part, judgment part and adjustment part are far away and not concentrated. If the code is long, it is difficult to judge and modify, and the for loop just solves this problem

### Grammatical structure

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

Use the for statement to implement the above code as follows:

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

You will find that the writing and use of the for statement are more convenient

### Execution process ### continue in for statement

Upper Code:

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

Can you think about the running result first?

analysis:

When i==5, execute continue, jump out of this cycle and execute the next cycle, so the following printf is not executed; In the next cycle, i + +, i becomes 6, i < = 10 is true, then the if statement judges that the condition is not true, does not execute continue, and then executes printf

Operation results: It can be found that there is a certain difference between the continue in the for statement and the continue in the for statement. The continue in the for statement will not skip i + +, while the continue in the while statement may skip i + + (it is easy to cause an endless loop)

### break in the for statement

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

analysis:

Here, when i==5, after the break is executed, the following printf will not be executed, and the whole for loop will jump out directly. The result should be 1 2 3 4

Operation results: ### 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". At this time, the judgment part behind the for statement is I < n, where n can represent 10 loops
```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

Variant 1

```#include <stdio.h>
int main()
{
//Variant 1
for ( ; ; )
{
printf("hehe\n");
}
}```

analysis:

This code is a direct loop. Why?

Because if the judgment part of the for loop is omitted, it is always true by default (it is recommended not to omit the initialization part, judgment part and adjustment part easily)

Variant 2

```#include <stdio.h>
int main()
{
//Variant 2
int x, y;
for (x = 0, y = 0; x < 2 && y < 5; ++x, y++)
{
printf("hehe\n");
}
return 0;
}``` Variant 2 is easy to understand. It's no longer wordy here

### Written test questions

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

analysis:

In the judgment part after the for statement, k = 0. Here, 0 is assigned to K, and then the value of K is 0, which is false. Therefore, the cycle is not carried out directly, and the number of cycles is 0

Operation results: ## 3. do... while loop

### Grammatical structure

```do
Loop statement;
while (expression);```

Now it is still printing 1-10, with the following code:

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

Compared with for statement and while statement, the most obvious feature of do... While statement is to execute first and then judge, execute once, and then judge whether to carry out the next loop, so the loop body will be executed at least once

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

### break in do... while statement

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

What is the result of this code?

analysis:

The loop body here contains a break. When i==5, the break directly jumps out of the loop, so the result should be 1 2 3 4

Operation results: ### continue in do... while statement

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

analysis:

Here, when i==5, execute continue, skip this cycle and proceed to the next cycle. In the later judgment part, i < = 10 is established and continue to enter the cycle. i has always been 5 (continue skipped the adjustment part i + +) and entered the dead cycle

Operation results: # 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 in some deeply nested structures, such as jumping out of two or more layers of 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.

See the following code:

```#include <stdio.h>
int main()
{
flag:
printf("hello\n");
printf("goodbye\n");
goto flag;
}```

analysis:

Goto in C language actually means where you want to go. When the code runs to goto, there is a flag behind it. Take the code and jump to the position of flag to execute. We will find that this actually constitutes a loop

## 1. Recommendations

It is not recommended to use goto statements in daily code writing. Although it can jump freely, if there are too many goto statements in a program and jump around, you may not be able to distinguish the logic of the code in the end, which will make the logic of the code confused and prone to problems  ## 2. Really suitable scenario

The really suitable scenario for goto statements should be to jump out of deep nested loops

Examples are as follows:

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

# 5, Search of integer ordered array

Let's practice circular statements through such cases

Now there is an integer ordered array arr  = {1,2,3,4,5,6,7,8,9,10}. Now we need to find a number in this array and return the following table of this element. How should we find it?

## 1. Traversal method

analysis:

We can compare each element in the array with the element we want to find. If it is the same, it means that it is found, and then return the subscript. If it is not the same, it will not be found. There is no element

code:

```#include <stdio.h>
int main()
{
int arr = { 1,2,3,4,5,6,7,8,9,10 };
int k = 0;
int i = 0;
printf("Please enter the number you want to find\n");
scanf("%d", &k);
for (i = 0; i < 10; i++)
{
if (k == arr[i])
{
printf("Yes, the subscript is%d\n", i);
break;
}
else
{
continue;
}
}
if (10 == i)     //If i==10, it means that all elements have been found, but still not found
{
printf("Can't find\n");
}
}```

Operation results:  You need to find it up to n times

It's too slow to compare ordered arrays one by one, so we can find them through the following dichotomy

## 2. Half / dichotomy

Premise of use: must be an ordered array

Because it is an ordered array search, we can narrow the range; Come and find it. It's faster

For example, in this arr array, I want to find 7, and if the middle number is 5, 5 is smaller than 7, then pass is lost before 1-5, and then in 6-10, the middle element 8 is found to be larger than 7, so 8-10 directly passes, and then in 6-7, the middle element 6, 6 is smaller than 7, so 6pass, and then find in 7. The left and right subscripts of 7 are 6, and the middle element is still 7, Then the element is found by comparison. In this way, the complexity is greatly reduced (half is eliminated every time)

code:

```int main()
{
int arr = { 1,2,3,4,5,6,7,8,9,10 };
int k = 0;
int size = sizeof(arr) / sizeof(int);
int left = 0;   //Left subscript
int right = size - 1;
int mid = 0;
printf("Please enter the number you want to find\n");
scanf("%d", &k);
do
{
mid = (left + right) / 2;
if (arr[mid] < k)
{
left = mid + 1;
}
else if (arr[mid] > k)
{
right = mid - 1;
}
else
{
printf("Yes, the subscript is%d", mid);
break;
}
} while (left <= right);
if (left > right)
{
printf("Can't find\n");
}
return 0;
}```  Find up to Log2 N

--------------------------------------------------------------------------------

-------------------------Branch and loop statement completion-----------------------------

About C language, each knowledge point will be introduced in more detail in a separate blog

Welcome to pay attention!!!

Learn and communicate together  !!!

Let's finish the programming!!!

--------------It's not easy to organize. Please support the third company-----------------

Tags: C Back-end Programmer

Posted on Fri, 19 Nov 2021 19:58:14 -0500 by zrosen88