4.3 Loop control statements
In the real world, there is such a phenomenon:
As long as the current oil in the tank is less than the tank capacity of 100 liters, the fuel tank has been refueling;
has been continuously for the motherland hard work, as long as I am still alive;
The company's 100,000 employees, everyone's wages increased by 10000 yuan;
Although these phenomena are different, they all have a common feature, that is, in a certain condition (as long as I am alive), or a certain range (all 100,000 employees), these movements (hard work, increase the salary of 10000 yuan) are repeated repeatedly in the cycle. To express this kind of cyclic phenomenon, C + + provides a loop control structure. Because of the characteristics of these cyclic phenomena, in order to accurately and simply express them, C + + has targeted to provide the while, do...while ... and a for statement.
4.3.1 while loop: as long as ... have been ...
For the first loop phenomenon above, we can use "as long as ..." Have been ... "this is a sentence to describe. In the real world, this cyclical phenomenon is very common:
As long as the sky is not black, has been working on the site;
As long as the hard disk has the remaining space, the file is stored on the hard drive.
In natural language, we use "as long as ... Have been ... "this kind of sentence to express this in a certain condition in a cycle of action cycle phenomenon, and in the corresponding, in C + +, we use the while loop structure to express the phenomenon of this cycle. The syntax format is as follows:
while (conditional expression) { loop-body statement;}
In a conditional expression, we judge a condition by a true or false value that indicates whether the condition is set or not, to express that the loop is under a certain condition. The loop body statement in the while structure represents the action that will be executed by the loop. For example, we will "as long as the current oil in the fuel tank capacity is less than 100 liters, the fuel tank has been refueling" this cycle phenomenon with the while structure expressed is:
// current oil volume NL = 0 // ... // while (NL < 100 + = 1 ; // Loop action: Add 1 liters of oil to the tank }
At execution time, the while statement first evaluates the value of the conditional expression (NL < 100), which is to determine whether the loop condition (the current oil content is less than 100 liters of the tank capacity) is satisfied. If the value is true, indicating that the loop condition is met, the loop executes the Loop body statement, completing the Loop action (adding 1 liters of oil to the tank), or conversely, indicating that the loop condition is no longer satisfied, thus directly ending the execution of the entire while statement. When the loop body statement finishes executing once, the value of the conditional expression is evaluated again to determine whether the loop condition is still satisfied. If it is satisfied, it continues into the loop execution loop body statement, starting the second loop. This repeats itself until the value of the conditional expression is false, and the loop condition is no longer satisfied, and the entire loop ends. The while can be understood as "as is" in natural language, as long as the loop condition is satisfied, the loop body statement is executed continuously. When the loop condition is no longer satisfied, the while Loop statement is ended. The execution of the while Loop statement is shown in process 4-3.
Learn more: Step through the execution program to see the code execution process
While the execution of a while loop statement is much more complex than the previously described if condition statement, plus the break and continue that we will learn later to control the execution process, so that the execution of the while Loop statement is more complex. A little attention may cause the actual execution of the code to be inconsistent with our design, which results in the execution of the program in error. In this case, we can take advantage of the single-step pilot function provided by Visual Studio to look at the true execution of the while Loop statement, to find a place that does not match the design expectations, and then correct the error so that the program executes the correct execution results according to the correct procedure.
The so-called single-Step debugging execution, is in the debugging state, according to the execution process of the program executes each statement sequentially, and in this process, we can clearly see the execution process of the program-which statement executed first, which statement after execution, which statement was skipped and not executed-- This determines whether the code executes in accordance with the design expectations. At the same time, we can also use the tool windows provided by Visual Studio to view the current values of each variable to see if the execution results match the design expectations. If the execution or execution results do not match the design expectations, this means that the code that is currently executing may be the place where the problem occurs in the program. When a program executes a problem, which is known as a bug, we often use this approach to find the code where the problem occurs and then fix it, and this process is called Debug.
To use single-step debugging to see the execution of a piece of code, we can first position the input focus at the beginning of the code, and then press the F9 shortcut key to set a breakpoint on the current line of code. A breakpoint is a code location that pauses during the execution of a program's debugging. After setting a breakpoint, press F5 shortcut key to debug the execution program, when the program executes to the breakpoint set before the position will be paused, then we can take advantage of the F10 shortcut key, press the key once to execute a statement, so you can see the entire code execution process. In this way, we can look at the execution of the while statement, thus having a deeper and more intuitive understanding of the execution of the while statement.
4.3.2 Do...while cycle: Always ... Just...
The while statement, described earlier, expresses the words "as long as ... have been ... "cyclic phenomenon, is" first to judge the cycle conditions after the execution of the cyclic action. " In the real world, however, there is another type of cyclical phenomenon. For example:
has been continuously for the motherland hard work, as long as I am still alive;
Always accept user input data, as long as the user input is not 0.
This kind of cyclic phenomenon is just the opposite of the loop phenomenon expressed by the while statement, which always executes the cyclic action (work, input data) and then determines the loop condition (still alive, the input is not 0). In natural language, we can use "always ... As long as ... "this kind of sentence to express this phenomenon, just is" as long as ... have been ... "upside down. Correspondingly, in C + +, we also invert the while statement to form Do...while ... Statement to express this cyclic phenomenon. The syntax format is as follows:
Do { loop body statement;} while (conditional expression);
At execution time, the Do...while loop statement executes the Loop body statement first, and then uses the conditional expression to judge the loop condition. If the value of the conditional expression is true, it means that the loop condition is still satisfied, the loop body statement can be executed again, the next loop is started, and conversely, it means that the loop condition is no longer satisfied and the entire loop is terminated directly. The execution of the Do...while Loop statement is shown in flow 4-4.
Let's look at a practical example. In life, budget-conscious moms always like to count monthly payments. Using natural language to describe the statistical process is to continuously enter the amount of revenue and expenditure and add it to the total amount of income, as long as there is the remaining amount of income and expenditure. Here, "There is the remaining amount of revenue" is do...while ... Cycle conditions, we use the input revenue and expenditure number of 0 to indicate that there is no remaining number, in other words, the cycle conditions become "as long as the amount of revenue is not 0". and "the number of inputs and the sum of revenue and expenditure" is the do...while ... Loop to repeat the action. This is a typical "always ... As long as ... "cycle phenomenon, with do...while ... The loop structure expresses it:
//monthly revenue and expenditure statistics procedure#include <iostream>using namespacestd;intMain () {//Output User Tipscout <<"====== Monthly revenue and expenditure statistics procedure ======"<<Endl; cout<<"Please enter your monthly income (positive) and expense (negative), 0 means end of input. "<<Endl; //number of revenues, the initial value here is not required intNinput =0; //Total revenue intNtotal =0; //first loop, unconditionally perform loop action//the loop that follows will be executed if the loop condition is met Do { //accept the number of user input and save to NinputCin>>Ninput; //The revenue and expenditure are counted, and the sum is added to the total revenue ntotalNtotal + =Ninput; } while(0! = ninput)//the loop condition is judged to determine whether the next cycle//Output Statistical Resultscout <<"your balance this month is:"<< Ntotal <<Endl; return 0;}
At the time of execution, do...while ... The first time the statement executes the loop body statement unconditionally, and then performs the condition judgment "while (0! = ninput)", judging whether the number of Ninput is 0, that is to say whether the cyclic condition is still satisfied, in order to decide whether to enter the next cycle. At this time the ninput is already the user's first input revenue and expenditure number, if it is 0, it means that there is no income and expenditure data, "0! = Ninput" value is False, the loop condition is no longer satisfied and directly end the entire do...while ... Loop statement. Instead, proceed to the next loop, accept the user input and add it to the total, and then again determine whether the loop condition is still satisfied to decide whether to proceed with the next cycle. This process will continue in a continuous cycle until the user enters Ninput 0 and the loop condition is no longer satisfied. The entire process only needs to enter the number of revenue and expenditure, the program will loop to receive the data and accumulate statistics to get results, which is more convenient than the calculator. Take this statistic program to your mom and you'll get a reward.
While and do...while are the structures used to express cyclic phenomena, and many times, they can be converted to each other. The difference between the two is that the while statement is the first to judge the cyclic condition after the execution of the cyclic action, and do...while ... The statement is exactly the reverse, which is the first step to judge the cyclic condition after the cyclic action. This also means that do...while ... The first loop of a statement can be executed unconditionally, so it is more appropriate to express which loops have no initial condition limit for the first loop. For example, in the revenue and expenditure statistics procedures for the first time to enter the amount of revenue and expenditure, any time any situation can be, there is no initial limitation. And every loop action of the while statement is executed on the premise that the loop condition is satisfied, so it is more suitable to express the cyclic phenomena which each loop has a precondition. For example, when refueling a car, every time we need to determine whether the tank is full, whether it is the first time or the last time.
Hello, C + + (21) As long as the day is not black, has been working on the site -4.3.1 while loop: As long as ... have been ...