[C Language] Loop statements while / for / do while / break and continue / goto statements

[C Language] Branching and Looping (Part 2)

  • 1. while loop
    • 1.1 Comparison between if and while
    • 1.2 Execution flow of while statement
    • 1.3 Practice of while loop
    • 1.4 Exercise
  • 2. for loop
    • 2.1 Grammatical form
    • 2.2 Execution process of for loop
    • 2.3 Practice of for loop
    • 2.4 Comparison between while loop and for loop
    • 2.5 Exercise
  • 3. do-while loop
    • 3.1 Grammatical form
    • 3.2 Execution flow of do while loop
    • 3.3 Examples of do while loop
    • 3.4 Exercise
  • 4. break and continue statements
    • 4.1 break and continue in while loop
      • 4.1.1 Example of break
      • 4.1.2 continue example
    • 4.2 break and continue in for loop
      • 4.2.1 Example of break
      • 4.2.2 continue example
    • 4.3 break and continue in do while loop
  • 5. Nesting of loops
    • 5.1 Exercise
    • 5.2 Question analysis
    • 5.3 Reference code
  • 6. goto statement

1. while loop

C language provides three loop statements, while is one of them. Next, we will introduce the while statement.

The syntactic structure of the while statement is very similar to that of the if statement.

1.1 Comparison between if and while

if(expression)
 statement;
 
 
while(expression)
 Statement;//If the loop body wants to contain more statements, you can add ? brackets

You can compare it and write a specific code.

//Code 1
#include <stdio.h>
int main()
{<!-- -->
if (1)
printf("hehe\\
"); //If the following conditions are met?, print hehe? times
return 0;
}
//Code 2
#include <stdio.h>
int main()
{<!-- -->
while (1)
printf("hehe\\
"); //The condition behind while is satisfied?, printing hehe in an infinite loop
return 0;
}

This is their difference. The while statement can achieve a loop effect.

1.2 Execution flow of while statement


The first step is to execute the judgment expression. If the value of the expression is 0, the loop ends directly; if the value of the expression is not 0, the loop statement is executed. After the statement is executed, the judgment continues to determine whether to perform the next judgment.

1.3 Practice of while loop

Exercise: Print values from 1 to 10 on the screen
Reference Code:

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

1.4 Exercise

Enter a positive integer and print each digit of this integer in reverse order.
For example:
Input: 1234, Output: 4 3 2 1
Input: 521, output: 1 2 5

Question analysis

  1. To get the lowest digit of n, you can use the operation n % 10, and the remainder is the lowest digit, such as: 1234 % 10 gets 4.
  2. If you want to remove the lowest digit of n and find the second to last digit, you can use n /= 10 operation to remove the lowest digit. For example, n = 1234 / 10 to get 123. Compared with 1234, the lowest digit is removed, 123 % 10 We get the penultimate digit 3.
  3. By looping through steps 1 and 2, all bits can be reached before n becomes 0.

Reference Code:

#include <stdio.h>
int main()
{<!-- -->
int n = 0;
scanf("%d", & amp;n);
while(n)
{<!-- -->
printf("%d ", n % 10);
n /= 10;
}
return 0;
}

2. for loop

2.1 Grammar Form

The for loop is the most commonly used among the three types of loops. The syntax of the for loop is as follows:

for (expression1; expression2; expression3)
     statement

Expression 1 is used to initialize loop variables
Expression 2 is used to determine the loop end condition
Expression 3 is used to adjust loop variables

2.2 Execution process of for loop


First, expression 1 is executed to initialize the loop variable, and then the judgment part of expression 2 is executed. If the result of expression 2 is == 0, the loop ends; if the result of expression 2 is != 0, the loop statement is executed. The loop statement After execution, execute expression 3 again, adjust the loop variables, and then go to expression 2 to perform judgment. Whether the result of expression 2 is 0 determines whether the loop continues.

During the entire loop process, the initialization part of expression 1 is only executed once, and the rest is expression 2, the loop statement, and expression 3 are recycled.

2.3 Practice of for loop

Exercise: Print values from 1 to 10 on the screen
Reference Code:

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

operation result:

2.4 Comparison between while loop and for loop



Both for and while have three parts: initialization, judgment, and adjustment in the process of implementing the loop. However, the three parts of the for loop are very concentrated, which facilitates the maintenance of the code. If there is a lot of code, the three parts of the while loop are It is relatively scattered, so the for loop is better in form.

2.5 Exercise

Exercise 1:

Calculate the sum of numbers that are multiples of 3 between 1 and 100

Reference Code:

#include <stdio.h>
int main()
{<!-- -->
int i = 0;
int sum = 0;
for (i = 1; i <= 100; i + + )
{<!-- -->
if (i % 3 == 0)
sum + = i;
}
printf("%d\\
", sum);
return 0;
}
//Optimization
//If we can directly produce numbers that are multiples of ?3, we will save redundant loops and judgments.
#include <stdio.h>
int main()
{<!-- -->
int i = 0;
int sum = 0;
for (i = 3; i <= 100; i + = 3)
{<!-- -->
sum + = i;
}
printf("%d\\
", sum);
return 0;
}

3. do-while loop

3.1 Grammar Form

The do while statement is the least used among loop statements. Its syntax is as follows:

do
    statement;
while (expression);

Both while and for loops are judged first. If the condition is met, it enters the loop and executes the loop statement. If it is not met, it jumps out of the loop;
The do while loop directly enters the loop body, executes the loop statement, and then executes the judgment expression after the while. If the expression is true, the next time will be executed. If the expression is false, the loop will not continue.

3.2 Execution flow of do while loop


In the do while loop, first execute the “statement” on the diagram. After executing the statement, execute the “judgment expression”. If the result of the judgment expression is !=0, then continue the loop and execute the loop statement; the result of the judgment expression ==0, the loop ends.

Therefore, in the do while statement, the loop body is executed at least once, which is a special aspect of the do while loop.

3.3 Example of do while loop

Print values from 1 to 10 on the screen

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


Generally do while is used in scenarios where the loop body is executed at least once, so it is less frequent.

3.4 Exercise

Enter a positive integer, how many digits does this integer have?
For example:
Input: 1234
Output: 4
Input: 12
Output: 2

Reference Code:

#include <stdio.h>
int main()
{<!-- -->
int n = 0;
scanf("%d", & amp;n);
int cnt = 0;
do
{<!-- -->
cnt + + ;
n = n / 10;
} while (n);
printf("%d\\
", cnt);
return 0;
}

It is not necessary to use the do while statement here, but this code is more suitable for using the do while loop, because even if n is 0, it is still a 1-digit number, and the number of digits needs to be counted.

4. break and continue statements

During the execution of the loop, if certain conditions occur, the loop needs to be terminated early. This is a very common phenomenon. The C language provides two keywords, break and continue, which should be used in loops.

  • The function of break is to permanently terminate the loop. As long as break is executed, it will jump out of the loop and continue execution.
  • The function of continue is to skip the code after continue in this loop, and there are all differences between the for loop and the while loop.

4.1 break and continue in while loop

4.1.1 break example

#include <stdio.h>
int main()
{<!-- -->
int i = 1;
while (i <= 10)
{<!-- -->
if (i == 5)
break;//When i equals 5, execute break and the loop ends.
printf("%d ", i);
i = i + 1;
}
return 0;
}

Execution result:

After printing 1, 2, 3, and 4, when i equals 5, the loop terminates at the break point and no longer prints or loops.

So the function of break is to permanently terminate the loop. As long as break is executed, the first layer of loop outside break will be terminated.

After that, if we are in the loop and want to terminate the loop under certain conditions, we can use break to achieve the desired effect.

4.1.2 Example of continue

continue means to continue. Its function in a loop is to skip the code after continue in this loop and continue to judge the next loop.

In the above code, what will be the result if break is replaced by continue?

#include <stdio.h>
int main()
{<!-- -->
int i = 1;
while (i <= 10)
{<!-- -->
if (i == 5)
continue;
//When i equals 5, execute continue, directly skip the continue code, and go to the loop judgment place?
//Because this skips i = i + 1, so i is always 5, and the program traps and infinite loop
printf("%d ", i);
i = i + 1;
}
return 0;
}

At this point we can analyze that continue can help us skip the code after continue in a certain loop and go directly to the judgment part of the loop to judge the next loop. If the adjustment of the loop is after continue, it may cause death. cycle.

4.2 break and continue in for loop

4.2.1 break example

In fact, like the break in the while loop, the break in the for loop is also used to terminate the loop. No matter how many times the loop needs to be executed, as long as break is executed, the loop will be completely terminated. Let’s go to the code.

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

operation result:

The function of break is to permanently terminate the loop. In the future, when a certain condition occurs and we no longer want to continue the loop, we can use break to complete it.

4.2.2 Example of continue

In the above code, what will be the result if break is replaced by continue?

#include <stdio.h>
int main()
{<!-- -->
int i = 1;
for (i = 1; i <= 10; i + + )
{<!-- -->
if (i == 5)
continue;//This?continue skips the subsequent printing and comes to the adjustment part of i++
printf("%d ", i);
}
return 0;
}


Therefore, the function of continue in the for loop is to skip the code after continue in this loop and go directly to the adjustment part of the loop. In the future, when a certain condition occurs and this loop no longer needs to perform certain subsequent operations, you can use continue to implement it.

Here we can also compare the difference between continue in while loop and for loop:

4.3 break and continue in do while loop

The functions of break and continue in the do while statement are almost exactly the same as those in the while loop. You can test and experience it yourself.

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

5. Nesting of loops

We have learned three types of loops before: while, do while, and for. These three loops are often nested together to solve the problem better. This is what we call: loop nesting. Here we will look at an example.

5.1 Exercise

Find the prime numbers between 100 and 200 and print them on the screen.
Note: A prime number, also known as a prime number, is a number that can only be divided by 1 and itself.

5.2 Question Analysis

  1. To find prime numbers between 100 and 200, you must first have numbers between 100 and 200. You can use a loop to solve this problem.
  2. Suppose you want to determine whether i is a prime number. You need to use numbers between 1 and i-1 to divide i. You need to generate numbers between 2 and i-1. You can also use a loop to solve this problem.
  3. If there is a number between 2~i-1 that can divide i, then i is not a prime number. If none of them can be divided, then i is a prime number.

5.3 Reference code

#include <stdio.h>
int main()
{<!-- -->
int i = 0;
//Cycle production? Numbers from 100 to 200
for (i = 100; i <= 200; i + + )
{<!-- -->
//Determine whether i is a prime number
//Loop to produce a number between 2~i-1
int j = 0;
int flag = 1;//Assume i is a prime number
for (j = 2; j < i; j + + )
{<!-- -->
if (i % j == 0)
{<!-- -->
flag = 0;
break;
}
}
if (flag == 1)
printf("%d ", i);
}
return 0;
}

6. goto statement

C language provides a very special syntax, which is the goto statement and jump label. The goto statement can jump to the set label within the same function.
For example:

#include <stdio.h>
int main()
{<!-- -->
printf("hehe\\
");
goto next;
printf("haha\\
");

next:
printf("Skip the printing of haha\\
");
return 0;
}

If the goto statement is used improperly, it will cause random jumps within the function and disrupt the execution flow of the program. Therefore, our suggestion is not to use it as much as possible; but the goto statement is not useless. In the code with multiple loops , if you want to jump out quickly, it is very convenient to use goto.

for (...)
{<!-- -->
for (...)
{<!-- -->
for (...)
{<!-- -->
if (disaster)
goto error;
}
}
 }
error:
//...

Originally, if you want to exit the for loop early, you have to use break. One break can only jump out of one level of for loop. If there are three levels of nested loops, you have to use 3 breaks to jump out of the loop. So in this case, it will be more convenient for us to use the goto statement. Fast.

over

That’s all I’ll share today
Looking for three consecutive rounds! ! !
Please pay attention! ! !