Branch loop statement, a blog will help you solve it

Foreword

After just entering the world of C, many students do not know much about the branch and loop structure statements of C language, so I would like to take this opportunity to talk about branches and loops in detail. Finally, I want my friends to understand after reading Can really apply these statements to programming. Learning these statements can actually solve many problems in the programming world.

Introduction statement

There are two types of branch statements in C: if statements and switch statements.

There are three types of loop statements in C: while loop, for loop and do…while loop

Next, I will describe the usage rules of these statements in order.

if statement

if(condition 1)//Only when the condition is met, it will enter from a statement, execute the corresponding module and then exit completely
{
    Operation statement;
}
else if (condition 2)//else if, else, etc. here can be omitted, and the number of else if is not limited, there can be multiple
{
    Operation statement;
}
else if(condition 3)
{
    Operation statement;
}
else //There can be at most one else in a branch statement, and it will be executed when all the above conditions are not met.
{
    Operation statement;
}

The above is the basic usage of the if statement. A curly bracket corresponds to the corresponding condition that matches it. After a set of operation statements are executed, other statements will not be executed and the if statement will be jumped out directly.

So you may ask: Can the curly braces be removed, like the following code?

if(condition 1)
    Operation statement;
else if(condition 2)
    Operation statement;
else if(condition 3)
    Operation statement;
else
    Operation statement;

Of course you can, but there is a restriction here that an if can only control one statement like the following

if (a==b) //It is wrong to write an if or else to control two statements like this
    a + + ;
    b=a;
else
    a--;
    a + =b;

If there are no curly braces, an if or else can only control the statement below it that is closest to it.

Next, I would like to ask you about a common mistake that beginners make. Let’s first take a look at what the following code will output after running it?

#include <stdio.h>
int main()
{
int a = 1;
if(a==0)
if(a==1)
printf("haha\\
");
else printf("hehe\\
");
return 0;
}

Maybe you will say: Isn’t this just a code that prints hehe? What else can I ask? However, I still recommend that you type the following code and run it to see what will be output.

The final result is that nothing will be output. On the surface, the first if and else are aligned, but in fact this is inconsistent with the matching rule of if else. else, else if matches its nearest if, and what really matches else is the second if. This depends on whether you can enter the branch statement of the first if at the beginning before you can further determine whether to output hehe .

Speaking of which, do you have a certain understanding of the branch statement if? Next, I will introduce to you the second branch statement: switch.

switch statement

Now I invite you to use programming to solve such a problem:

Enter a number less than 8 to print the seven days of the week.

Maybe you will write the following code

#include <stdio.h>
int main()
{
int a;
scanf("%d", & amp;a);
if(a==1)
printf("Monday\\
");
else if (a == 2) {
printf("Tuesday\\
");
}
else if//Omit the following
. . . . .
return 0;
}

But, wouldn’t this be a bit complicated? So there are statements like switch to solve the above problems.

Look at the following switch statement application code

#include <stdio.h>
int main()
{
int a;
scanf("%d", & amp;a);
switch (a) {
case 1://if a==1
printf("day1\\
");
case 2://if a==2
printf("day2\\
");
case 3:
printf("day3\\
");
case 4:
printf("day4\\
");
case 5:
printf("day5\\
");
case 6:
printf("day6\\
");
case 7:
printf("day7\\
");
default:// will be entered from here when the first 7 input items do not exist.
printf("wrong\\
");
}
return 0;
}

So what will be the output after inputting 5?

bd1960047e2743859df7f90a93bed80e.png

You can see that after day5 is output, day6 is output continuously until it is wrong. What is going on?

It turns out that in the switch statement, case only represents an entry that satisfies the condition. After the current statement is executed, the execution will continue. So how to avoid this situation? Let’s look at the following code again

#include <stdio.h>
int main()
{
int a;
scanf("%d", & amp;a);
switch (a) {
case 1:
printf("day1\\
");
break;
case 2:
printf("day2\\
");
break;
case 3:
printf("day3\\
");
break;
case 4:
printf("day4\\
");
break;
case 5:
printf("day5\\
");
break;
case 6:
printf("day6\\
");
break;
case 7:
printf("day7\\
");
break;
default:
printf("wrong\\
");
}
return 0;
}

The use of the break statement can solve this problem and allow the program to jump directly from the switch statement, so that the above situation will not occur again.

Now I will ask another question:

If you enter 1-5 to print working days and 6-7 to print rest days, how should you handle the program?

You may say, why is this so difficult? Change the first five outputs to workday and the last two to weekend.

But in fact it can be simplified more, look at the following code

#include <stdio.h>
int main()
{
int a;
scanf("%d", & amp;a);
switch (a) {
case 1:
case 2:
case 3:
case 4:
case 5:
printf("workday\\
");
break;
case 6:
case 7:
printf("weekend\\
");
break;
default:
printf("wrong\\
");
}
return 0;
}

The above code solves this problem very well

Finally, let’s introduce the following switch. The order between case and default in it is interchangeable. At the same time, what follows the case must be a character (enclosed in single quotes, such as: ‘a’) or a number or a floating point. If the type is placed later, an error will be reported.

while loop

while(loop condition){
    execute statement;
}

When the loop condition is met, the statements within the curly brackets below will be executed.

Will run only if the loop condition returns non-0

The main thing to pay attention to is not to forget to adjust the conditions when executing the loop to prevent falling into an infinite loop.

for loop

Let’s first look at the for loop format

for (initialization; condition; adjustment statement) {
    execute statement;
}

The for loop is also one of the more commonly used loops in programming.

I want to give you a basic understanding of the for loop through a picture first.

d80e059c132a4adc85fbcdd62a10aa65.jpg

Since the blogger is not very good at using drawing tools, he directly uses writing to show the running process of the for loop. In fact, if you carefully observe the for loop and while loop, it may not be difficult to find that for is actually a necessary condition for the loop. A collection that includes variable initialization, conditional judgment and variable adjustment after each cycle, which greatly simplifies the code. It is also a statement that is used relatively frequently in practical applications and problem solving.

Another thing to remind is that the initialization, condition change and condition judgment in the parentheses after for can be omitted, but omitting condition change and condition judgment can easily lead to an infinite loop, so it is recommended that beginners do not omit these contents at will. , and then adjust as needed after you become proficient in using it later.

do…while statement

This statement is actually similar to the while statement. The while statement first determines whether the condition is met and then runs the statement, while do…while runs the statement first and then determines whether to continue running the statement in a loop. The application is as follows

do {
    execute statement;
} while (execution condition);

The do…while statement is actually relatively rarely used in actual programming. Most problems can be solved using while and for loop statements.

At this point, we have almost introduced branch and loop statements. There is one more thing to tell you. These branches and loops can be nested, which actually greatly improves the flexibility of the code.

Nesting between statements

Next I will introduce nesting with a code that filters prime numbers between 100-200

#include <stdio.h>
int main()
{
for (int i = 100; i <= 200; i + + ) { //Initialize i to enumerate each number from 100-200
int flag = 1;//Initialize a flag. When flag==1, it means that i is a prime number at this time.
for (int j = 2; j <= i - 1; j + + ) {//Check whether i is a prime number
if (i % j == 0) {
flag = 0;//If it is not a prime number, set it to 0
break;
}
}
if (flag == 1)//Gorgeous printing
printf("%d ", i);
}
return 0;
}

This code not only nests loops, but also nests branch statements, which perfectly demonstrates the flexibility of statements. You can type it by yourself or secretly CV my code to try it.

In fact, the prime number judgment can be further optimized. I would like to ask if you find that you can actually screen out all the prime numbers before j reaches the root sign i. We can replace i-1 with sqrt(i), The function of this function is to take the square root of a number and finally return the derived value. However, don’t forget the header file #include before calling this function, otherwise this function cannot be called.

About loop control statements

Have you noticed before that I used a statement like break? In fact, this is a control statement for a loop. Similar statements include continue and goto. Next, I will introduce them to you.

break

Break is actually used relatively often in programs. When you want to jump out of a loop directly, you can call this statement. You can look at the code I just put above for screening prime numbers. break is used in it, which can make it Jump out directly from the for (int j=2; j<=i-1;j + +) loop. The same is true for while, do...while and other loop applications.

continue

The role of continu in a loop is to directly end the current loop and enter the next loop. You can look at the following code

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

The result of running this program is 0 1 2 3 4 6 7 8 9. This is because when i==5, the following statements are directly skipped through continue and i++ is directly run. After judging i<10, it enters the next loop. , while and do...while are the same, except that the statement i + + is missing.

goto

goto is a statement that can be adjusted arbitrarily in the program. Take a look at the code below.

#include <stdio.h>
int main()
{
printf("hehe\\
");
goto jump1;//Jump1 here is just a jump label, what name you choose depends on your mood
printf("lala\\
");
jump1:;//This is the jump exit
printf("haha\\
");
return 0;
}

The final printed result is as follows

You can see that lala is skipped directly when the program is running. Such a jump is a basic usage of goto.

Reasonable use of goto and abuse of goto

Finally, let’s talk about goto. In fact, many books and technicians today criticize goto for its low logic, and it is easy to disrupt the idea and adjustment of a code. My suggestion here is to avoid using goto, but sometimes use it. It is relatively efficient when jumping out of multi-level loops.

I want to show you the effects of abusing goto. This is a Luogu 1205 question I did. I apologize for using goto indiscriminately, but in the end the question was successfully AC. Without further ado, let’s take a look at the source code.

#include <stdio.h>

char primitive[11][11];
char trans[11][11];
char ultimate[11][11];
int main()
{
int n;
scanf("%d\\
", & amp;n);
for (int i = 1; i <= n; i + + ) {
for (int j = 1; j <= n; j + + ) {
scanf("%c", & amp;primitive[i][j]);
}
scanf("\\
");
}
for (int i = 1; i <= n; i + + ) {
for (int j = 1; j <= n; j + + ) {
scanf("%c", & amp;ultimate[i][j]);
}
scanf("\\
");
}
for(int i=1;i<=n;i + + )
for (int j = 1; j <= n; j + + ) {
if (primitive[i][j] != ultimate[j][n - i + 1]) { goto end1; }
}
printf("%d", 1);
return 0;
end1:;
for(int i=1;i<=n;i + + )
for (int j = 1; j <= n; j + + ) {
if (primitive[i][j] != ultimate[n - i + 1][n - j + 1]) { goto end2; }
}
printf("%d", 2);
return 0;
end2:;
for (int i = 1; i <= n; i + + )
for (int j = 1; j <= n; j + + ) {
if (primitive[i][j] != ultimate[n-j + 1][i]) { goto end3; }
}
printf("%d", 3);
return 0;
end3:;
for (int i = 1; i <= n; i + + )
for (int j = 1; j <= n; j + + ) {
if (primitive[i][j] != ultimate[i][n-j + 1]) { goto end4; }
}
printf("%d", 4);
return 0;
end4:;
for (int i = 1; i <= n; i + + )
for (int j = 1; j <= n; j + + ) {
trans[i][j] = primitive[i][n - j + 1];
}
for (int i = 1; i <= n; i + + )
for (int j = 1; j <= n; j + + ) {
if (trans[i][j] != ultimate[j][n - i + 1]) { goto out1; }
}
goto end5;
out1:;
for (int i = 1; i <= n; i + + )
for (int j = 1; j <= n; j + + ) {
if (trans[i][j] != ultimate[n - i + 1][n - j + 1]) { goto out2; }
}
goto end5;
out2:;
for (int i = 1; i <= n; i + + )
for (int j = 1; j <= n; j + + ) {
if (trans[i][j] != ultimate[n - j + 1][i]) { goto out3; }
}
end5:;
printf("%d", 5);
return 0;
out3:;
for (int i = 1; i <= n; i + + )
for (int j = 1; j <= n; j + + ) {
if (primitive[i][j] != ultimate[i][j]) { goto end6; }
}
printf("%d", 6);
return 0;
end6:;
printf("%d", 7);
return 0;
}

The questions are no longer displayed here. If you are interested, you can go to Luogu Search and have a look.

End

Thank you friends who read my blog attentively. A blog is really too labor-intensive, and your whole body will explode. If this blog is helpful to you, please give it a small like and add it to your favorites. It’s me. Great motivation to move forward. Not much to say, I’m off to do my advanced math homework. . .