Chapter 10 cyclic statements
10.1 WHILE LOOP
10.2 do... while loop
10.3 For Loop
10.3.1 three elements of cyclic conditions
10.3.2 the three elements are embodied in the For Loop Structure
10.4 multi-layer Loop
10.5 summary and a few questions
Loop is repetition.
There are many things that need to be repeated in life. For example, you and my whole life is a repetition, repeating every day until we die. Fortunately, our daily life is not exactly the same.
10.1 WHILE LOOP
Syntax format:
While (condition)
{
Statements that need to be executed cyclically;
}
While is the meaning of "when.
First, make a comparison with the if statement:
If (condition)
{
Statement executed when the condition is set;
}
Except for the different keywords, the two have the same structure. Note that when the condition is set, the IF statement is executed only once, and the while statement is executed repeatedly until the condition is no longer true.
See the while loop flowchart:
The program starts execution from the "previous statement" and then determines the conditions. If the conditions are true, the program executes the "Statement executed in each loop". Pay special attention to the red part after that, this is what we met. For the first time, we will go back to the process: the red line is like a car turning, turning around to the condition (not including the previous statement), and then making the next condition judgment ...... The program "continues the following statement" until the condition is invalid during a certain judgment ".
We use the while syntax to apply the actual examples in our daily life. We can intuitively see the usage of while.
Suppose there is a crying little doll. One day she asks her parents to buy a red dress. Unfortunately, her parents do not agree, so she starts a cycle:
While (parents do not buy a red dress)
{
I cried;
}
This "code" means that when "My parents don't buy a red dress", the little girl will cry over and over again.
This is the first battle between us and the loop process. The example above seems intuitive: "Children cry over and over again until their parents buy a dress", but it must be considered in many aspects to use the language of the program to correctly express it, the program is rigorous.
First,A suitable condition for determining whether to continue is very important.The little girl will continue to cry, just "My parents don't buy a red dress for me". This shows that it is not in line with the facts. When we were young, we would cry again and eventually get tired, to continue crying, we have two conditions: "My parents don't buy a red dress" and "I'm not tired yet ".
While (my parents do not buy a red dress & I have not been tired of crying)
{
I cried;
}
Second, in most cases,The condition needs to be properly changed.The little girl is crying constantly. How does she know whether her parents have bought a red dress? Therefore, she can't just cry, but she has to observe whether adults agree to buy a dress while crying. As for whether to cry tired, let's assume that the little girl has a fatigue. Each time she cries, the fatigue increases by 1. When the fatigue reaches 200, the poor little girl is tired ......
While (parents do not buy small red skirts & fatigue <200)
{
I cried;
I peeked at whether my parents agreed to buy a dress;
Fatigue ++;
}
Example 1: Use the while statement to calculate the sum from 1 to 100.
For the sum of 1 + 2, we can write a = 1 + 2; for the sum of 1 to 100, we can write a = 1 + 2 + 3 +... 100. however, this is obviously too tiring to write data from 1 to 100! Therefore, if you are smart like Gauss, you certainly know this: A = (1 + 100) * 50; this is indeed worthy of praise at any time, the fast and simple method is that today we want to make the computer tired, from 1 to 100 honestly. First, use the while loop we learned first.
Open CB, create a blank console program, and add the following code to the main () function body. Then press F9 to run. View the running result to make a deeper impression.
//---------------------------------------------------------------------------
# Include <iostream. h>
# Pragma hdrstop
//---------------------------------------------------------------------------
# Pragma argsused
Int main (INT argc, char * argv [])
{
Int sum = 0; // The variable sum will be used to store the sum and initialize it to 0, which is very important.
Int I = 1; // I is the number to be added each time. It starts from 1.
While (I <= 100)
{
Sum + = I;
I ++;
}
// Output the accumulative result:
Cout <"1 to 100 sum:" <sum <Endl;
Getchar ();
}
Sum is initially 0, and then in each loop, it adds I, and I is added after each addition, increase by 1. In the end, I increases to 101 and exceeds 100. This cycle completes the task.
Run the above program and the output result is:
The sum between 1 and 100 is: 5050.
Example 2: Use a while loop to implement simple statistical functions
Statistical functions are often used in various industries, such as the total score of school students and the daily sales of stores. Next we will calculate the score of a student.
Because the score contains a decimal part such as 80.5, we use the real number type.
Save, close the project above, and create a new console project. Add the following code to the main function:
//---------------------------------------------------------------------------
# Include <iostream. h>
# Pragma hdrstop
//---------------------------------------------------------------------------
# Pragma argsused
Int main (INT argc, char * argv [])
{
Float sum, score;
Int num; // num is used to store statistics on several scores.
Int I; // I used for counting
// Initialization:
Sum = 0;
I = 1;
Cout <"= score statistics program =" <Endl;
// You need to enter the total score in advance:
Cout <"Enter the number of scores to be calculated :";
Cin> num;
Cout <"enter a total of" <num <"scores (enter the Enter key after each score):" <Endl;
While (I <= num)
{
Cout <"Enter the" <I <"score :";
Cin> score;
Sum + = score;
I ++;
}
// Output the statistical result:
Cout <"Number of scores included in the statistics:" <num <Endl;
Cout <"total score:" <sum <Endl;
Getchar ();
}
//---------------------------------------------------------------------------
Here are the running results. I enter 4 scores for statistics:
Press enter to end the above program. Take a break.
To better understand the loop process, we can now track the while loop in this program.
1. Set the breakpoint at the beginning of the loop (F5 function ):
2. Press F9 to run the program. When the DOS window prompts "Enter the number of scores to be calculated:", enter 4 and press Enter.
3. The program will immediately run to the row where the breakpoint set in the first step is located. That is, the while (...) line.
In this case, move the mouse over I. Wait a moment and the prompt "I = 1" appears. You can observe the num value in the same way.
It can be seen that during the first loop, I = 1, num = 4, condition: I <= num is obviously true, and the loop can continue.
4. Press F8 to run the program one line down, and then press F8. Enter a score as required by the program. Switch to the DOS window, enter a number as needed, and press Enter.
After you press enter, the program runs to the blue bottom line:
5. Then, press F8 consecutively and you will find that the program "returns" and runs to the while (...) line. At this time, the I = 2, I <= num condition is still true. If you want to track the loop again, continue to press F8. If you want to end the trail, press F5 again on the breakpoint line to cancel the breakpoint, and then press F9 to restore the program to full speed.
(The program goes back and returns to the while line)
10.2 do... while loop
Syntax format:
Do
{
Statements that need to be executed cyclically;
}
While (condition );
The most obvious difference between a while loop and a while loop is that in a do... while loop, the condition for determining whether or not to continue the loop is placed at the end. That is to say, even if the condition is not true at the beginning, the loop will be executed once. Compare the following two sections of code: the former uses the while loop, and the latter uses the do... while loop.
Code snippet 1:
Int A = 0;
While (a> 0)
{
A --;
}
The initial value of variable A is 0, and the condition a> 0 is obviously not true. Therefore, the --; statement in the loop body is not executed.
After the code is executed, the value of variable A is still 0;
Code Segment 2:
Int A = 0;
Do
{
A --;
}
While (a> 0 );
Although the condition a> 0 is not true before loop execution, but because the program is running to do... instead of judging the conditions, run the statement in the loop body: --. So the value of a becomes-1, and then the program judges a> 0. It finds that the condition is not true and the loop ends.
Do .. the condition in while is the same as that in the while loop: "the condition that allows the loop to continue", rather than "the condition that ends the loop". This is the same as do... the opposite is true for until. If you have learned Pascal (Delphi), you can pay attention to it.
Based on my experience, do... while loops are not used much. Most loops are implemented more intuitively using while. Below we simply convert the 1-100 concatenation program to do... while:
Int sum = 0;
Int I = 1;
Do
{
Sum + = I;
I ++;
}
While (I <= 100 );
Example 3: Use do... while to implement the program that can be measured multiple times.
In Example 2, we made a statistical program. If a student has three scores, such as Chinese, mathematics, and English, to calculate the total score, the procedure of Example 2 can be easily used, but if you want to continuously count the scores of each student in a class, we have to keep running the result of example 2, which is obviously inconvenient.
The three scores of one student require a loop. To continuously count the scores of multiple students, you need to set a loop. In the example below, how can I add a do... while loop to the original while... loop.
The idea of the program is: after the statistics are completed, ask whether to continue to count the scores of new students. If you enter the letter y or Y, you need to count the bit. Otherwise, program end loop.
This program is to improve the function on the basis of example 2, the bold section below is the newly added code.
//---------------------------------------------------------------------------
# Include <iostream. h>
# Pragma hdrstop
//---------------------------------------------------------------------------
# Pragma argsused
Int main (INT argc, char * argv [])
{
Float sum, score;
Int num; // num is used to store statistics on several scores.
Int I; // I used for counting
Char C; // used to receive letters entered by the user
Do
{
// Initialization:
Sum = 0;
I = 1;
Cout <"= score statistics program =" <Endl;
// You need to enter the total score in advance:
Cout <"Enter the number of scores to be calculated :";
Cin> num;
Cout <"enter a total of" <num <"scores (enter the Enter key after each score):" <Endl;
While (I <= num)
{
Cout <"Enter the" <I <"score :";
Cin> score;
Sum + = score;
I ++;
}
// Output the statistical result:
Cout <"Number of scores included in the statistics:" <num <Endl;
Cout <"total score:" <sum <Endl;
// Ask whether to continue statistics:
Cout <"Start new statistics? (Y/n )? ";
Cin> C;
}
While (C = 'y' | C = 'y ');
}
//---------------------------------------------------------------------------
After the program completes a statistics, it will ask "do you want to start a new statistics?". The user enters a letter, stores it in variable C, and then the program runs in do... in the while condition, check whether C is equal to 'y' or 'y '. If not, the loop ends.
Since the program has a time to ask a question after statistics, the original getchar () is no longer needed.
In this example, the use of do... while in the outer loop is the best option, because the user wants to count at least once when running the program.
Finally, let's take a look at the flowchart of the do... while loop. Please compare it with the while flowchart.
10.3 For Loop
For loops use the most in C and C ++, and are also the most flexible loop statements. To learn it well, you need to "mine" the elements of the loop flow from the while loop that you have learned. These elements are hidden in the while, or do... while, but it will be directly reflected in the structure of the for loop.
10.3.1 three elements of cyclic conditions
After learning two cycles, we can explore the "three conditions" in the cycle process ".
First, the condition usually requires initialization.
Please refer to the code that uses the while loop to accumulate 1 to 100:
Int sum = 0; // The variable sum will be used to store the sum and initialize it to 0, which is very important.
Int I = 1; // I is the number to be added each time. It starts from 1.
While (I <= 100)
{
Sum + = I;
I ++;
}
In this Code, the condition for loop is I <= 100; therefore, at the beginning, I must have a definite value. Previous:
Int I = 0; this line of code, while declaring the variable I, also assigned an initial value for I: 1. In this way, condition I <= 100 is true (because I is 1, I <= 100 is true ).
Second, the loop must have a chance to end.
The "endless loop" is the most taboo in the program ". The so-called "endless loop" means that the loop condition is always true, and there is no chance to jump out of the loop (which will be learned later ). For example:
// An example of an endless loop:
While (2> 1)
{
Cout <"endless loop" <Endl;
}
Run this code and you will find that the program cannot stop. The reason is that its cycle condition 2> 1 is always true. Therefore, a final condition that can be changed to an invalid condition is required in most cases. For example, in the while example:
While (I <= 100)
Condition I <= 100, Because I is changed in the loop, it may at least theoretically cause I <= 100 to be invalid.
Third, the establishment factor of changing the cycle condition in the loop
This article matches the second article.
For example, this Code:
Int I = 1;
While (I <= 100)
{
Sum + = I;
}
It is also a terrible "endless loop ". Because I has no chance of being changed, its value is always 1, so that the cyclic condition I <= 100 is always true. Therefore, the last sentence (bold below) in the loop cannot be forgotten.
While (I <= 100)
{
Sum + = I;
I ++;
}
Of course, in this program, in addition to the factors that change the conditions, I ++ also increases the sum continuously, so as to accumulate and.
After reading this, we can see the most flexible loop structure in C ++: For Loop.
10.3.2 the three elements are embodied in the For Loop Structure
For Loop Syntax:
For (condition initialization; condition change)
{
Statements that need to be executed cyclically;
}
It can be seen that in the for structure, not only the "condition" location is provided, but also the condition initialization and the location where the condition changes. Although the three are on the same line, they are not sequentially executed.
The conditional initialization expression is executed first (and only once );
Then, the program checks whether the conditions are true. If the conditions are true, the statement in the loop body is executed. Otherwise, the loop ends directly.
After a loop is executed, the program executes the "conditional change" statement.
The program that accumulates integers from 1 to 100 is changed to for loop writing, which is the most suitable:
Int sum = 0;
Int I;
For (I = 1; I <= 100; I ++)
{
Sum + = I;
}
The program first executes the conditional initialization statement: I = 1;
Then, can I determine the condition I <= 100 immediately? Display. The condition is true;
Therefore, the program executes the statement in the loop body. At this time, there is only one sentence: Sum + = I;
Then, execute the statement to change the condition factor: I ++; at this time, the I value is changed to 2;
The program judges the condition again I <= 100 ?, Still valid, so the second loop ......
Variable I can be declared temporarily only when the conditions are initialized:
For (INT I = 1; I <= 100; I ++ )......
The compound structure of the for statement makes the program simple. For example, in the above example, the original while or do... in the while structure, there must be two statements in the loop body. Now you only need one sentence (that is, the I ++ sentence is moved to a specific position of the For). In this way, we can remove curly braces:
For (INT I = 0; I <= 100; I ++)
Sum ++ = 100;
Of course, if, in other cases, the for loop body still needs to have multiple rows of statements, {} is still unavoidable. In fact, even in this situation, we recommend that you use curly brackets. This makes the program structure clearer.
In this example, we can move the only row in the circular body to the position of "condition change" if we have to make it simple:
For (INT I = 1; I <= 100; sum + = I, I ++ );
Sum + = I and I ++ are separated by commas. The end of the () line after the for statement is followed by a semicolon, indicating that the for statement does not have to be executed.
Considering the post ++ feature (adding 1 after the expression is evaluated), you can also combine sum + = I and I ++ into one sentence:
For (INT I = 1; I <= 100; sum + = I ++ );
The above describes how to merge for statements in a simple way. In turn, the for statement can be opened and written in the same way as the while or do... while statement:
Int I = 1;
For (; I <= 100 ;)
{
Sum + = I;
I ++;
}
Check that the conditional initialization statement is removed from the for structure, and the conditional change statement is treated as a normal statement and directly added to the loop body. In the corresponding position, only the semicolon is left to indicate the null Statement (note that there are two semicolons in this line, before and after I <= 100 ):
For (; I <= 100 ;)
As shown in the uplink, the expressions "Conditional initialization" and "conditional change" in the for loop structure are ignored. In this case, the for and do... while loops are exactly the same. For example, 1 ~ 100 sum:
Int I = 1, sum = 0; For (; I <= 100 ;) { Sum + = I; I ++; } |
Int I = 1, sum = 0; While (I <= 100) { Sum + = I; I ++; } |
The following describes several instances: (the instances used for analysis do not provide complete code for the machine. Ask the students to create a blank project and add the required Code to ensure that each instance can run, this is the only way for beginners to gradually become proficient ...... Believe it or not. Open CB ).
Question 1:Use for loop to output numbers on the screen line by line: 1 ~ 200.
Analysis:This requires a variable whose value is changed from 1 to 200. Each time a new value is changed, the cout statement is used to output the value on the screen.
Answer:
For (INT I = 1; I <= 200; I ++)
Cout <I <Endl;
Because there is only one action in the loop, we omit {}.
Question 2:6 can be divisible by 1, 2, 3, and 6. These numbers are called 6 factors. Please list all 36 factors cyclically.
Analysis:Factor? Forgot? The factor of 36 is 1 ~ Which integers in 36 can be divided by 36. We have learned the % operator, which is used to calculate the remainder of the division of two numbers. Therefore, you only need to check whether the remainder is 0.
Answer:
For (INT I = 1; I <= 36; I ++)
{
If (36% I = 0) // the remainder is 0, indicating the Division
Cout <I <""; // multiple outputs a space for the interval between two numbers.
}
If you run the program, the result is:
1 2 3 4 6 9 12 18 36
In this question, we also see the combination of the two processes: the for loop process and the if condition branch process. The solution to complex problems is often the combination of conditional flows and cyclic flows. The multi-layer loops described below are also one of these combinations.
10.4 multi-layer Loop
Some problems can be solved only by multi-layer nested loops. The previous program that can be measured multiple times uses a two-tier loop. The do... while clause of the outer layer implements repeated statistics, and the while loop of the inner layer implements one statistics.
Continue to analyze some questions:
Question 3:Two methods are required to output the following content. The first method adopts a single-layer loop, and the second method adopts a double-layer loop.
123
456
789
Method 1:
Analysis:The idea of a single-layer loop is: output from 1 to 9, and each time three numbers are output, one line break is output.
Answer:
For (INT I = 1; I <= 9; I ++)
{
Cout <I;
If (I % 3 = 0) // use the remainder operation again.
Cout <Endl;
}
Method 2:
Analysis:The idea of a double-layer loop is to output three rows, each row outputs three numbers.
Answer:
For (INT I = 1; I <= 3; I ++)
{
For (Int J = I; j <= I + 3; j ++)
{
Cout <J;
}
Cout <Endl;
}
In the code, the inner for is used to output numbers for each row, while the outer for is used to output a line break after each row is output. note that the condition initialization of the inner loop is related to the outer loop. That is, Int J = I; is exactly. Each time an inner loop starts, the J value starts from the current I value.
This question seems to be a reference to solving everything with a single-layer loop, because it seems that using a double-layer loop is not very intuitive?
Question 4:Output the following content:
1
12
123
1234
12345
123456
1234567
12345678
123456789
As soon as the question came out, I saw a classmate jump into the code and quickly output the correct content on the screen. His answer is:
Cout <"1" <Endl;
Cout <"12" <Endl;
Cout <"123" <Endl;
Cout <"1234" <Endl;
Cout <"12345" <Endl;
Cout <"123456" <Endl;
Cout <"1234567" <Endl;
Cout <"12345678" <Endl;
Cout <"123456789" <Endl;
If someone gives such an answer in a loop job, I'm going to give him a "duck egg.
No one will have to use a loop to solve this problem unless they are unable to do so, but most intuitive ). This topic uses a double loop to achieve the best solution.
Analysis:The outer loop is used to control the output of nine rows, and the inner loop is used to output the numbers of each row. Each row starts from 1, but the first row outputs 1 number, the second row outputs 2, and the third row outputs 3 ......
Answer:
For (INT I = 1; I <= 9; I ++)
{
For (Int J = 1; j <= I; j ++)
{
Cout <J;
}
Cout <Endl;
}
In this example, the condition initialization of the inner loop has nothing to do with the outer loop, but the judgment of the condition is related to the I of the outer loop (j <= I ). Of course, this is not a necessary condition, but the condition initialization or condition judgment of the inner loop is related to some factors in the outer loop. This is the key to solving many multi-layer loops! Continue with a classic question.
Question 5:Output the following table:
1*1 = 1
1*2 = 2 2*2 = 4
1*3 = 3 2*3 = 6 3*3 = 9
1*4 = 4 2*4 = 8 3*4 = 12 4*4 = 16
1*5 = 5 2*5 = 10 3*5 = 15 4*5 = 20 5*5 = 25
1*6 = 6 2*6 = 12 3*6 = 18 4*6 = 24 5*6 = 30 6*6 = 36
1*7 = 7 2*7 = 14 3*7 = 21 4*7 = 28 5*7 = 35 6*7 = 42 7*7 = 49
1*8 = 8 2*8 = 16 3*8 = 24 4*8 = 32 5*8 = 40 6*8 = 24 7*8 = 56 8*8 = 64
1*9 = 9 2*9 = 18 3*9 = 27 4*9 = 36 5*9 = 45 6*9 = 36 7*9 = 63 8*9 = 72 9*9 = 81
Analysis:You can see that this question is very similar to Question 4. It is to output a "Triangle" (strictly a trapezoid ?), So the idea for solving the problem is roughly the same: Output nine rows. You may say that nine columns can be output, right? Yes, but we can use the console (DOS) window for output now, so it is limited to output from top to the next row, rather than from left to right columns.
Since it is output by line, let's look at the characteristics of each line of content:
The output content of each row is: I * j = K, where K is a product, determined by I and j, so we don't have to look at it:
Row 1st: 1*1. There is only one. It does not show any characteristics.
Row 3: 1x2x2 ...... 1, 2 multiplied by 2
Row 3: 1*3 2*3*3 ...... 1, 2, 3 multiplied by 3
Therefore, the rule of the content of each row is: if the current row is set to the line, the output N * line, n is 1 to line.
For (INT line = 1; line <= 9; line ++)
{
For (INT n = 1; n <= line; line ++)
{
Cout <n <'*' <line <'=' <n * line <'';
}
Cout <Endl;
}
Change line to I and N to J. The circular control part of this question is exactly the same as question 4.
To understand the above analysis questions, the best way is to actually run the machine, and then run it step by yourself by pressing F8. So again, the content of this chapter can be ended, but if you do not have to operate these cycle questions on the computer, you cannot say that you have learned this chapter well.
10.5 summary and a few questions
I learned three types of loop processes: while, do... while,.
While checks whether the condition is true at the beginning of each loop. If the condition is not true at the beginning, the statement in the loop is not executed at one time.
The special feature of do... while is that the condition is not checked before the first loop, so even if the condition is not true, the loop will be executed once, for example:
Do
{
...
}
While (false );
Is the condition "false "? Is that a condition? Yes, this is also a condition. It is a condition that is not valid. It is also common: While (0 ). 0 indicates false. On the contrary, the true condition is: While (true) or while (1.
The special feature of for is that in addition to condition judgment, it also explicitly sets aside the location of condition initialization and condition change. Therefore, the counting cycle is most suitable for using for. For more information, see the example of using for to accumulate between 1 and 100 in the course.
As for the various "variants" of for, you only need to understand it. It will not be too late to sell it.
A loop is like a circle. For example, in a physical education class, we run 1200 meters and 400 meters in a circle, so what we need to do is to count them in our hearts while we are running (of course we need to count the number, otherwise, the teacher should take a few laps in case, when the Count reaches 3, the "loop" ends.
In this example, when the condition is initialized, the count is set to 0; the condition of the cycle is that the count is smaller than 3; the condition change means that when every lap is completed, the count is added to 1; as for the loop action, it is naturally a running ......
Implement with while:
Int JS = 0; // JS stands for "Counting", not "profiteering" or "sentence God"
While (JS <3)
{
Run a lap ......;
JS ++;
}
Use do... while to implement:
Int JS = 0;
Do
{
Take a lap ......
JS ++;
}
While (JS <3 );
Use for (most suitable)
For (INT I = 0; I <3; I ++)
{
Run a lap ......;
}
If, unfortunately, I fainted when I was running ...... What should I do? See the next chapter!