Hello, C ++ (21) as long as the day is not dark, it has been working on the site-4.3.1 while loop: as long... Always ..., -4.3.1

Source: Internet
Author: User

Hello, C ++ (21) as long as the day is not dark, it has been working on the site-4.3.1 while loop: as long... Always ..., -4.3.1
4.3 loop control statement

In the real world, there is such a phenomenon:

As long as the current fuel volume in the fuel tank is less than the fuel tank capacity of 100 liters, it will continue to add oil to the fuel tank;

I have been working hard for the motherland, as long as I am still alive;

The company has 100000 employees, and each employee's salary has increased by 10000 yuan;

Although these phenomena are different, they all share a common feature, that is, under a certain condition (as long as I am still alive) or within a certain range (all 100000 employees, these actions (hard work and an increase of 10000 yuan) are repeated multiple times. C ++ provides a loop control structure to express such loops. Because these loops have their own characteristics, in order to express them accurately and easily, C ++ provides the while, do... While... And for statements.

4.3.1 while loop: as long... Always...

For the first cycle phenomenon above, we can use "as long... Always ..." Such a sentence to describe. In the real world, this cycle is very common:

As long as the day is not dark, he has been working at the construction site;

As long as there is still space on the hard disk, you can store files on the hard disk.

In natural language, we use... Always ..." Such a sentence is used to express the cycle of an action loop under a certain condition. In C ++, we use the while loop structure to express this loop phenomenon. The syntax format is as follows:

While (condition expression) {loop body statement ;}

In a condition expression, we determine a condition to obtain the true or false values indicating whether the condition is true or false. In this way, this loop is implemented under "A condition. The loop body statement in the while structure indicates the action that will be executed cyclically. For example, we will keep adding oil to the tank as long as the current fuel volume in the tank is less than 100 liters in the tank capacity. "This circulation phenomenon is expressed in the while structure:

// Current oil volume int nL = 0 ;//... // Cycle condition: the current fuel volume is smaller than the tank volume while (nL <100) {nL + = 1; // cycle action: Add 1 litre of oil to the tank}

During execution, the while statement first calculates the value of the condition expression (nL <100), that is, to determine whether the cycle condition (the current fuel volume is less than 100 litre of the tank capacity) is met. If its value is true, it indicates that the cycle condition is met, then the loop body statement is executed cyclically to complete the cycle action (adding 1 litre of oil to the tank); otherwise, it indicates that the cycle condition is no longer met, to directly end the execution of the while statement. After the loop body statement is executed once, the value of the condition expression is calculated again to determine whether the loop condition is still met. If yes, the system continues to execute the loop body statement and starts the second loop. This repeats until the value of the conditional expression is false and the cycle condition is no longer met. The whole loop ends. The while statement can be interpreted as "as long as" in the natural language. As long as the loop condition is met, the loop body statement is continuously executed. When the loop condition is no longer met, the while LOOP statement ends. The execution process of the while LOOP statement is 4-3.

Learn more: debug the execution program in one step and view the Code Execution Process

The execution process of the while LOOP statement is much more complex than the if condition statement described earlier. In addition, we will learn the break and continue to control the execution process, in this way, the execution of the while LOOP statement is more complicated. If you do not pay attention to it, the actual execution process of the Code may be inconsistent with our design, which leads to incorrect execution results. In this case, we can use the single-step test run function provided by Visual Studio to view the real execution process of the while LOOP statement, so as to locate the inconsistency with the design expectation and correct the error, make the program run according to the correct process to obtain the correct execution result.

One-step debugging is to execute each statement one by one according to the execution process of the program in the debugging state. In this process, we can clearly see the execution process of the program-which statement is executed first and which statement is executed later, which statement is skipped but not executed? This determines whether the Code Execution Process matches the design expectation. At the same time, we can also use the "Observation" and "variable" tool windows provided by Visual Studio to view the current values of each variable, determine whether the execution result is consistent with the design expectation. If the execution process or execution result is inconsistent with the design expectation, this means that the Code being executed may be a problem in the program. When there is a problem in program execution, that is, when a bug occurs, we usually use this method to locate the problematic code and correct it. This process is also called debug.

To use single-step debugging and execution to view the execution process of a code segment, we can first locate the input focus at the beginning of the code segment, press the F9 shortcut to set a breakpoint in the current code line. The so-called breakpoint is the position of the code that will be paused during program debugging and execution. After the breakpoint is set, press the F5 shortcut key to debug and execute the program. When the program is executed to the previously set breakpoint location, it will be paused. At this time, we can use the F10 shortcut key to press the button to execute a statement downward, this shows the entire code execution process. In this way, we can view the execution process of the while statement, so as to have a deeper and more intuitive understanding of the execution process of the while statement.

4.3.2 do... While loop: Always... As long...

The while statement described above expresses "as long... Always ..." Loop phenomenon: "First Judge the cycle condition and then execute the loop action ". However, there is another kind of cyclical phenomenon in the real world. For example:

I have been working hard for the motherland, as long as I am still alive;

Always accept user input data, as long as the user input is not 0.

This kind of loop phenomenon is just opposite to the loop phenomenon expressed by the while statement. It always runs the loop action (work, input data) first and then judges the loop condition (still alive, input is not 0 ). In natural language, we can use... As long ..." Such a sentence to express this phenomenon, just as long... Always ..." . Correspondingly, in C ++, we also put the while statement upside down to form do... While... Statement. The syntax format is as follows:

Do {loop body statement;} while (conditional expression );

During execution, do... The while LOOP statement first executes a loop body statement and then uses a condition expression to judge the loop condition. If the value of the conditional expression is true, it means that the loop condition is still met. You can execute the loop body statement again to start the next loop. Otherwise, it means that the loop condition is no longer met, directly end the entire loop. Do... The execution process of the while LOOP statement is 4-4.

The following is a practical example. In our daily life, budget-calculated mothers always like to count the monthly income and expenditure. To describe this statistical process in natural language, we constantly enter the amount of income and expenditure and accumulate it to the total amount of income and expenditure, as long as there is still the remaining amount of income and expenditure. Here, "the remaining amount of Income and Expenditure" is do... While... The number of Income and Expenditure input is 0, indicating that there is no remaining number. In other words, the cycle condition is "as long as the number of income and expenditure is not 0 ". "Enter the amount of income and expenditure and add it to the total amount of Income and Expenditure" is this do... While... The action to be executed repeatedly in a loop. This is a typical "always... As long ..." Loop phenomenon, use do... While... The loop structure expresses it as follows:

// Monthly revenue and expenditure statistics program # include <iostream> using namespace std; int main () {// output the user prompt cout <"====== monthly revenue and expenditure statistics program ====" <endl; cout <"Enter your income (positive number) and expenditure (negative number) for this month. 0 indicates that the input is over. "<Endl; // number of income and expenditure, the initial value here is not a required int nInput = 0; // total number of Income and Expenditure int nTotal = 0; // The first cycle, unconditionally execute the loop action // The subsequent loop. do can be executed only when the cycle condition is met. {// accept the number of Income and Expenditure input by the user and save it to nInput cin> nInput; // calculate the income and expenditure, and add it to the total number of Income and Expenditure nTotal + = nInput;} while (0! = NInput) // judge the cycle condition to determine whether to perform the next cycle // output the statistical result cout <"your balance for this month is: "<nTotal <endl; return 0 ;}

During execution, do... While... For the first time, the statement will unconditionally execute a loop body statement before executing the condition judgment "while (0! = NInput) "to determine whether the number of Income and Expenditure nInput is 0, that is, to determine whether the cycle condition is still met to determine whether to enter the next cycle. At this time, nInput is the number of income and expenditure that the user enters for the first time. If it is 0, there is no income and expenditure data in the end. "0! = NInput "is set to false, and the entire do... While... Loop statement. Otherwise, continue to the next cycle, accept user input and accumulate it to the total revenue and expenditure, and then determine whether the cycle condition is still met to determine whether to carry out the next cycle. This process continues cyclically until the user input nInput is 0 and the cycle condition is no longer met. Throughout the process, you only need to enter the amount of income and expenditure. The program will receive the data cyclically and accumulate the statistics to get the results. This is much easier than simply using a calculator. Let's take this statistical program to our mom. It will certainly be rewarded.

While and do... While is a structure used to express cyclic phenomena. In many cases, they can be converted to each other. The difference between the two is that the while statement first judges the loop condition and then executes the loop action, while the do... While... The statement is the opposite. Execute the loop action first and then judge the loop condition. This means that do... While... The first loop of a statement can be executed unconditionally, so it is more suitable for expressing loop phenomena with no restrictions on the initial conditions of the first loop. For example, when the number of income and expenditure is input for the first time in the income and expenditure statistics program, it can be used in any situation at any time without any initial conditions. Each loop action of the while statement must be executed when the loop condition is met. Therefore, it is more suitable for expressing loop phenomena with the precondition for each loop. For example, every time we refuel a car, we need to determine whether the tank is full, whether it is the first time or the last time.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.