Scenario review
Previous review: Getting Started with C Tutorial: How to Use While Loops to Implement Repetitive Execution**.
This section focuses on:
This section focuses on how to use a do while loop statement, and what is the difference between it and a while loop statement?
C is a widely used programming language that is concise, efficient, and flexible. There are a variety of loop statements in the C language that are used to repeat a paragraph of ** until a certain condition is met. In this article, we'll look at a type of loop statement in C:do while loop statement.
Contrast:
while statement and do....The difference between while statements is that while statements check the conditions before each loop, do....The while statement checks the condition after each loop. This can also be seen from the ** of the two loop structures, where the while statement in the while structure appears in front of the loop body, do....The while statement in the while structure appears after the loop body.
do while loop:
In some cases, the cyclic process must be performed at least once, regardless of whether the conditions are met or not, in which case do....while statement. do…The characteristic of a while statement is that the content of the loop statement block is executed first, and then the loop condition is determined to be true.
The basic format of a do while loop statement is as follows:
do while (conditional expression);
The execution of the do while loop statement looks like this:
First, execute the ** in the loop body once.
Then, the value of the conditional expression is determined, and if it is true (non-zero), it proceeds to the ** in the loop bodyIf false (zero), the loop ends.
Repeat the above steps until the value of the conditional expression is false (zero).
The do while loop statement is characterized by:
** in the loop body is executed at least once, because the conditional expression is judged after the loop body is executed.
There must be a semicolon (;) between the loop body and the conditional expression) indicates the end of the loop statement.
The application scenarios of the do while loop statement are:
When ** in the loop body needs to be executed at least once, you can use the do while loop statement.
When the number of loops is uncertain, but rather determined by conditional expressions, you can use a do while loop statement.
Here's an example of using a do while loop statement:
#include int main() while (n > 0); printf("The sum of the positive integers entered is: %d", sum); return 0;}The function of this program is to continuously enter positive integers from the keyboard until a non-positive integer is entered, and then output the sum of all input positive integers. The result of the program is as follows:
Please enter a positive integer: 10Please enter a positive integer: 20Please enter a positive integer: 30Please enter a positive integer: 0The sum of positive integers entered is: 60C Language Basics