You are watching: The do-while loop is a pre-test loop.
The while Loop
The when loop has two necessary parts: (1) an expression that is tested because that a true or false value, and also (2) a declare or block the is repeated as lengthy as the expression is true. The figure listed below shows the logic of a while loop.
In the basic format, (expression) is any type of expression that deserve to be evaluated together true or false, and statement; is any kind of valid C++ statement. The an initial line displayed in the figure over is referred to as the loop header. It consists of the key word while adhered to by one expression enclosed in parentheses. Here’s just how the loop works: the (expression) is tested, and also if it is true, the statement(s) are executed. Then, the (expression) is experiment again. If it is true, the statement(s) are executed. This bike repeats until the (expression) is false. The statement(s) the is repetitive is well-known as the body of the loop. The while loop works favor an if statement that executes over and also over. As lengthy as the expression inside the clip is true, the body of the loop will repeat. The program below uses the if loop to print “Hello” 5 times.
// This routine demonstrates a basic while loop.#include using namespace std;int main() int number = 0;while (number cout number++; cout return 0;This regime tests the variable number to determine whether it is less than 5. If that is, climate the explanation in the body that the loop are executed. The statement number++; in the body that the loop uses the increment operator to add one come number. This is the critical statement in the body that the loop, therefore after it executes, the loop starts over. It tests the expression (number again, and if that is true, the explanation in the body of the loop space executed again. This bicycle repeats till the expression (number is false. Each repetition of a loop is recognized as one iteration. This loop will certainly perform five iterations due to the fact that the change number is initialized through the value 0, and it is incremented every time the body that the loop is executed. Once the expression (number is tested and also found to be false, the loop will terminate and also the program will resume execution in ~ the statement that immediately follows the loop. The figure listed below shows the logic of this loop.
In this example, the number change is described as the loop regulate variable because it controls the variety of times the the loop iterates. The while loop is well-known as a pretest loop, which way it test its expression before each iteration.
Loops must contain within themselves a means to terminate. This means that something within the loop must eventually make the check expression false. The loop in the example over stops when the expression (number is false. If a loop go not have actually a method of stopping, the is called an boundless loop. An infinite loop continues to repeat till the regime is interrupted. Below is an instance of an unlimited loop:
int number = 0;while (number cout This is an infinite loop since it does no contain a statement that alters the worth of the number variable. Each time the expression (number is tested, number will certainly contain the worth 0. That also feasible to produce an limitless loop by accidentally placing a semicolon ~ the an initial line of the while loop.
int number = 0;while (number cout number++The semicolon at the end of the very first line is suspect to be a null statement and disconnects the if statement indigenous the block that comes after ~ it. Come the compiler, this loop look at like:
while (number This while loop will certainly forever execute the null statement, which walk nothing. The regime will appear to have “gone right into space” due to the fact that there is nothing to display screen screen output or show activity.
The do-while Loop
The do-while loop watch something choose an inverted when loop. The figure listed below shows the logic of a do-while loop.
The do-while loop is a posttest loop. This method it does not test that is expression until it has actually completed one iteration. Together a result, the do-while loop always performs at the very least one iteration, also if the expression is false to begin with. This differs from the behavior of a while loop, which you will certainly recall is a pretest loop.
The for Loop
In general, there are two category of loops: conditional loops and also count-controlled loops. A conditional loop executes as long as a particular condition exists. Because that example, an entry validation loop executes as lengthy as the input value is invalid. Once you compose a conditional loop, you have no means of understanding the variety of times it will iterate.
Sometimes you recognize the exact number of iterations that a loop need to perform. A loop that repeats a specific variety of times is recognized as a count-controlled loop. Because that example, if a loop asks the user to get in the sales amounts for each month in the year, it will certainly iterate twelve times. In essence, the loop counts to twelve and also asks the user to get in a sales amount each time it provides a count. A count-controlled loop need to possess 3 elements:It need to initialize a counter variable come a starting value.It should test the counter variable by to compare it come a best value. When the counter variable will its best value, the loop terminates.It should update the respond to variable throughout each iteration. This is commonly done through incrementing the variable.
Count-controlled loops space so common that C++ offers a type of loop particularly for them. The is recognized as the for loop. The for loop is specifically designed to initialize, test, and also update a counter variable. Here is the layout of the because that loop as soon as it is used to repeat a block is:
The an initial line of the for loop is the loop header. After the key word for, there space three expressions inside the parentheses, be separated by semicolons. (Notice over there is not a semi- colon after the 3rd expression.) The an initial expression is the initialization expression. That is usually used to initialize a respond to variable come its beginning value. This is the an initial action carry out by the loop, and also it is just done once. The second expression is the test expression. This is one expression the controls the execution that the loop. As long as this expression is true, the human body of the because that loop will certainly repeat. The for loop is a pretest loop, therefore it evaluates the test expression prior to each iteration. The 3rd expression is the update expression. That executes at the end of every iteration. Typically, this is a statement the increments the loop’s counter variable.
Here is an instance of a simple for loop the prints “Hello” 5 times:
for (int counting = 0; count cout In this loop, the initialization expression is counting = 0, the test expression is count , and also the upgrade expression is count++. The body the the loop has actually one statement, i m sorry is the cout statement. Figure listed below illustrates the succession of events that take away place throughout the loop’s execution. Notification that procedures 2 through 4 are recurring as long as the check expression is true.
Notice just how the counter variable, count, is used to control the variety of times that the loop iterates. During the execution that the loop, this change takes on the values 1 v 5, and also when the test expression count is false, the loop terminates. Also an alert that in this instance the count variable is provided only in the loop header, to control the number of loop iterations. That is not offered for any other purpose. It is also feasible to use the respond to variable in ~ the human body of the loop. Because the for loop exam its check expression prior to it performs an iteration, the is a pretest loop.Deciding which Loop come Use
Each that the three C++ loops is best to use in different situations. Here’s a short summary of when each loop need to be used.The while loop. The while loop is a conditional loop, which way it repeats as long as a details condition exists. It is also a pretest loop, so the is ideal in situations where you execute not want the loop to iterate if the condition is false native the beginning. For example, validating input that has been read and reading perform of data terminated through a sentinel worth are good applications the the if loop.The do-while loop. The do-while loop is also a conditional loop. Unequal the while loop, however, do-while is a posttest loop. It is ideal in cases where you constantly want the loop come iterate at the very least once. The do-while loop is a good choice for repeating a menu.The for loop. The for loop is a pretest loop that has built-in expressions because that initializing, testing, and updating. These expressions make it really convenient to usage a counter variable to manage the variety of iterations that the loop performs. The initialization expression deserve to initialize the respond to variable come a beginning value, the check expression have the right to test the counter variable to identify whether the holds the maximum value, and the upgrade expression can increment the counter variable. The because that loop is right in situations where the exact number of iterations is known.Optional Topics: Breaking and also Continuing a Loop
Sometimes it’s crucial to protect against a loop prior to it goes through all its iterations. The rest statement, which was used with move in chapter 4, can likewise be placed inside a loop. When it is encountered, the loop stops, and the regime jumps come the statement automatically following the loop.
The while loop in the complying with program segment shows up to execute 10 times, however the break statement reasons it to prevent after the 5th iteration.
int counting = 0;while (count++ cout if (count == 5) break;Using break in a Nested Loop
In a nested loop, the rest statement just interrupts the loop that is put in. The complying with program segment screens five rows of asterisks ~ above the screen. The outer loop controls the number of rows, and the inside loop controls the variety of asterisks in each row. The inner loop is designed to display screen 20 asterisks, however the rest statement stop it throughout the eleventh iteration.
for (int row = 0; row for (int star = 0; star cout if (star == 10) break; cout The continue Statement
The proceed statement reasons the current iteration of a loop to finish immediately. When continue is encountered, every the statements in the human body of the loop that appear after it room ignored, and also the loop prepares for the following iteration.
See more: Adidas Manchester United Jersey 15 16 Away White Jersey, Adidas Manchester United 15/16 Home Jersey
In a while loop, this means the regimen jumps to the test expression at the optimal of the loop. As usual, if the expression is tho true, the next iteration begins. In a do-while loop, the routine jumps come the check expression in ~ the bottom the the loop, which determines whether the following iteration will certainly begin. In a because that loop, continue causes the upgrade expression to it is in executed and then the check expression to be evaluated.
The adhering to program segment demonstrates the usage of proceed in a while loop:
int testVal = 0;while (testVal++ if (testVal == 4) continue; cout This loop looks favor it display screens the integers 1 v 10. As soon as testVal is same to 4, however, the proceed statement causes the loop to skip the cout statement and begin the following iteration. The output of the loop is