Hello, C + + (22) row, eat fruit--4.3.3 for loop: In a range ... Each of them ...

Source: Internet
Author: User

4.3.3 for Loop: Within a range ... Each of them ...

Since the while statement and Do...while ... Statements have been able to meet the needs of our expression loop phenomenon, why should C + + specifically provide a For statement to express the loop phenomenon? In the real world, there are often such a special kind of cyclic phenomena, such as:

Within the company's 100,000 employees, each employee increased the salary of 10000 yuan;

In the range from 1 to 100, each number is summed up into the sum.

These are cyclical phenomena, because their movements (increased wages, accumulation) will be repeated over and over again and again. They are special because they are always executed within a certain range (100,000 employees, ranging from 1 to 100) for each of these elements (each employee increases and each number accumulates). In natural language, we can use "a certain range ... Every ... "This type of sentence expresses this kind of cyclic phenomenon in a certain range. And because it is very common, in order to express this kind of cyclic phenomenon more conveniently, C + + is specialized in providing a For loop structure statement. In C + +, the syntax format for the For loop structure is as follows:

 for (initialization statement; conditional Judgment statement; Change statement) {    loop body statement;}

A For loop statement is a loop phenomenon within a range, so there is often a circular index that moves in the same loop as a cursor, allowing it to sequentially access individual elements within the loop range. And the three statement after the FOR keyword is to manipulate the cyclic index so that it moves around the loop within a certain pattern, thus traversing the entire loop range. In specific terms:

1. Initialize statements

The initialization statement is executed once when the FOR Loop statement executes, primarily to define the loop index value and initialize it to the starting position of the loop range. In other words, it determines the starting point of the loop range. For example, "int i = 1" is a typical initialization statement that defines the cyclic index value I and assigns it a value of 1, which means that the loop starts at 1 (in C + +, we tend to use 0 as the starting point for the loop).

2. Conditional Judgment Statement

As the start of each loop, the conditional judgment statement is executed once, and if its value is true, the loop body statement continues to execute downward. Conversely, the execution of the entire for loop is terminated directly. Therefore, it is used primarily to determine whether the loop index value is within the end of the loop range. If within the range, the value of the conditional judgment statement is that the TRUE,FOR Loop statement will begin the next loop to continue execution of the loop body statement. Conversely, if the loop index value is outside the end of the loop range, the value of the conditional statement is that the False,for loop will no longer continue and end the entire for loop directly. In this sense, it determines the end of the cycle range. For example, "I <= 100" is a typical conditional judgment statement that, before each loop starts, determines whether the loop index i is within 100 of the end of the loop range to determine whether to start the execution of the loop body statement, thus limiting the loop to the loop range.

3. Change statements

The change statement is executed at the end of each loop body statement, and is used primarily to modify the cyclic index value so that it gradually changes from the start of the loop to the end of the loop, in accordance with a certain rule. In this process, we can access each element within the loop range based on this changing cyclic index value, which is often referred to as a traversal of elements within the loop range. For example, the change statement for "++i" is to have the cyclic index I increment by 1 after each loop, so that it moves one step to the end of the loop range. In this way, the cyclic index I can gradually increment from the loop start 1 to the end of the loop 100, so that we have access to each element within the loop range.

Best practice: Pay attention to the processing of cyclic conditions to avoid the formation of a dead cycle

The so-called cycle of death is the chance that the loop does not end, and that it will be executed again and again forever. Any loop must end the loop under certain conditions, or because the value of the conditional judgment statement is false and the loop ends, or the loop is terminated within the loop with the break keyword in a certain condition, there must be an opportunity to end the loop, or it will become a dead loop that continues to execute. Causes the code behind the loop to not be executed, and naturally it will not get the correct result. For example, in the previous example, the conditional judgment statement of "0! = Ninput" has the opportunity to have its value become fasle, which is when the user enters a value of Ninput of 0. So, this cycle has an opportunity to end without becoming a dead loop.

The end of the loop is often determined by the conditional judgment statement, so we should take extra care when dealing with conditional judgment statements. If handled improperly, it can cause the value to always be true regardless of how it is executed, so that the loop never has a chance to end and form a dead loop. For example:

// a dead loop formed by improper processing of conditional judgment statements // forgot the change statement, but can still compile the  for (int010000;) {    cout<<"I Love you! "<<Endl;}

The intent of this procedure is to say 10,000 times "I Love you!" Pretending to be a saint, and forgetting to change the cyclic index i in the change statement so that the value of the cyclic index i is always the original 0, and the value of the conditional judgment statement "i<10000" is always true, the loop never ends and becomes a dead loop, and the result is a nagging "I love you! "Nature will only be treated as a fool." If you do not want to be a fool from the feelings of the holy, then take good care of our conditional judgment statement, as far as possible to avoid the emergence of the death cycle.

The three statements after the FOR keyword are processed by the loop condition, and the loop body statement is the loop action. At the time of execution, the for loop executes the initialization statement first, then the conditional judgment statement, and if its value is true, means that the current loop condition is satisfied, it starts to execute the Loop body statement down, and then executes the change statement to modify the circular index value, and then executes the bar judgment statement again. To determine whether the loop condition is still satisfied and, if satisfied, starts the next loop. This process will continue to loop until the condition evaluates to False and the loop condition is no longer satisfied. The For loop is executed as shown in procedure 4-5.

Throughout the loop, the value of the circular index changes from the start of the loop to the end of the loop in a certain order, which means that the values of the circular index are constantly changing in each loop, and with these constantly changing index values, we have access to the individual data within the loop range. For example, "ntotal + = i;" is a typical loop body statement, each time the loop, it will loop the index value I plus and to ntotal, and the value of the cyclic index value I is from 1 (int i = 1) to (I <= 100) gradually increment (++i), This is equivalent to ntotal in turn 1, 2, 3 ... 99, 100, the last thing that is naturally obtained is the sum of all integers from 1 to 100.

Following our analysis of the various parts of the for loop, we can draw a For loop that calculates all integers from 1 to 100:

//calculates the and of all integers from 1 to 100//Records and ValuesintNtotal =0;//use the For loop to add integers from 1 to 100 one by one with Ntotal for(inti =1;//Cycle StartI <= -;//End of Cycle++i)//Cyclic index value change law{    //accumulate integersNtotal + =i;} cout<<"1 to 100 of all integers and yes"<<nTotal<<endl;
4.3.4 Cycle control: Break and Continue

Although the cycle of the phenomenon will continue to execute continuously, but also encountered an unexpected situation when the cycle was broken. For example:

have been constantly working hard for the motherland, as long as I am alive. But if you get sick, you have to retire early.

The company's 100,000 employees, in addition to people over 50 years of age, the rest of the wages of each person increased by 10000 yuan;

Here, the phenomenon of "illness" and "Age over 50", break the original cycle, is the exception of the cycle phenomenon, need special treatment, some need to terminate the cycle prematurely (sick retirement), some need to skip the loop body Execution (no increase in wages) and directly start the next cycle. To describe exceptions in the loop, C + + provides two keywords: break and continue.

1. Break

The break keyword has been introduced when introducing the switch side-by-side conditional selection statement, which is the end of the entire switch statement execution. Similarly, when it is used in a looping structure, its role is also to end the current loop control statement and continue executing the next statement after the loop statement. In this way, we can use it to express the cyclical phenomena that need to be terminated prematurely due to exceptional circumstances. For example, it is used to express the cyclical phenomenon of "early retirement" due to the exception of "sickness":

//is alive.BOOLBalive =true;//Are you sick ?BOOLBsick =false; while(balive)//Judging if it's alive.{    if(Bsick)//Judging if you are sick{cout<<"Sick of early retirement"<<Endl;  Break;//end the cycle prematurely because of an exception to illness} cout<<"work hard for the motherland"<<Endl; //Change loop control conditions balive ...}//... ..

When the loop body statement is executed, the IF condition is used first to determine whether the disease is ill, that is to say whether the exception occurred. If an exception occurs, the value of Bsick becomes true, the program executes inside the IF condition statement, and when the break keyword is encountered, it jumps out of the loop and ends the execution of the entire loop. In this way, the IF condition statement is responsible for judging whether an exception occurred, and the break keyword is responsible for ending the loop prematurely when an exception occurs. The combination of the two is a good way to express the cyclical phenomena that need to end prematurely due to exceptional circumstances.

We can look at a practical example, or the Revenue and expenditure statistics program, and we can rewrite it with the break keyword:

intNtotal =0;intNinput =0; Do{cout<<"Please enter your income or expenses:"; CIN>>Ninput; //The input data is judged,//If this exception is 0, the input ends and the entire loop is ended with the break keyword    if(0==ninput) Break; //In normal circumstances, the number of revenue and expenditure will be added to the totalNtotal + =Ninput;}  while(true);//use True as a loop condition, indicating that the loop ends in an internal exception

Here, we use true as Do...while ... The conditional judgment statement of the loop statement, but this is not a "dead loop", because it has the opportunity to end the loop, that is, when the user input ninput is 0 o'clock, the program will enter the "if (0 = = ninput)" Conditional statement execution, encountered in which the break keyword will end the entire loop, Thus avoiding the cycle of becoming dead. At the same time, it also expresses the handling of the exception of the "number of inputs for 0": ending the entire cycle. After such a rewrite, the loop statement can accept the user's input indefinitely, but when the user wants to end the input, only need to enter 0 to meet the "0 = = Ninput" This unexpected condition, the execution of the break keyword can end the entire loop execution.

2. Continue

The break keyword ends the entire loop under certain conditions, while the Continue keyword ends the execution of the loop body under certain conditions (that is, all the loop body statements that are skipped after the Continue keyword), and then proceeds directly to the next loop. If it is while or do...while ... Loop, it directly determines whether the loop condition is satisfied to start the next loop, and if it is a for loop, then executes the change statement and then determines whether the loop condition satisfies to start the next loop. Or use the above income and expenditure statistics example, if a big money is less than 10000 yuan of the penny does not care, only want to statistics greater than or equal to 10000 of income and expenditure, you can use the Continue keyword to rewrite the program as follows:

//income and expenditure statistics procedure for wealthyintNtotal =0;intNinput =0; Do{cout<<"Please enter your income or expenses:"; CIN>>Ninput; //if it's less than 10000, don't count.    if((Ninput >-10000) && (Ninput <10000) )        Continue;//Skip the back loop body statement without countingNtotal+=Ninput;}  while(0! = Ninput);

In this rich's revenue and expenditure statistics program, when Ninput receives user input data, we use if condition statement to determine whether its value is less than 10000. If it is less than the penny that is not counted, then execute the Continue keyword in the IF condition statement, skipping the following add and statistic statement "ntotal + = Ninput;" Execution does not include its statistics, but jumps directly to the calculation of the conditional expression "0! = ninput" To determine whether the next loop can be started. In this way, it is very good to express the special treatment of the exception of "the number of income and expenditure less than 10000": to end this cycle, not to count it.

In summary, break and continue are often mixed with conditional statements, which are responsible for judging exceptions, while they express the handling of exceptions: Break jumps out of the loop, immediately ends the loop control statement, and continue only jumps out of the loop, End the execution of this loop and continue with the next loop. Figure 4-6 shows the difference between break and continue.

Figure 4-6 the difference between break and continue

Hello, C + + (22) row, eat fruit--4.3.3 for loop: In a range ... Each of them ...

Related Article

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.