In vault post, we talked about the ide of control structures, which straight the flow of a program. A loop is a manage structure that causes a statement or team of statements to repeat. C++ has actually three looping control structures: the while loop, the do-while loop, and also the for loop. The difference in between these structures is exactly how they control the repetition.

You are watching: The while loop is a pretest loop

The while Loop

The if loop has actually two vital parts: (1) one expression the is tested for a true or false value, and also (2) a statement or block the is repeated as lengthy as the expression is true. The figure listed below shows the reasonable of a when loop.


*

*

*

In the general format, (expression) is any expression that deserve to be evaluated together true or false, and statement; is any type of valid C++ statement. The very first line shown in the figure above is referred to as the loop header. It is composed of the crucial word while complied with by an expression enclosed in parentheses. Here’s just how the loop works: the (expression) is tested, and if it is true, the statement(s) space executed. Then, the (expression) is experiment again. If that is true, the statement(s) are executed. This bicycle repeats until the (expression) is false. The statement(s) the is recurring is well-known as the body of the loop. The while loop works choose an if statement the executes over and over. As lengthy as the expression within the parentheses is true, the body of the loop will repeat. The program listed below uses the while loop to publish “Hello” 5 times.

// This routine demonstrates a basic while loop.#include making use of namespace std;int main() int number = 0;while (number cout number++; cout return 0;This routine tests the variable number to identify whether it is much less than 5. If it is, then the statements in the body of the loop space executed. The declare number++; in the body the the loop uses the increment operator to include one come number. This is the last statement in the body of the loop, so after that executes, the loop beginning over. The tests the expression (number again, and also if that is true, the statements in the body that the loop are executed again. This bike repeats until the expression (number is false. Every repetition that a loop is recognized as one iteration. This loop will certainly perform 5 iterations due to the fact that the change number is initialized v the worth 0, and also it is incremented each time the body of the loop is executed. When the expression (number is tested and also found to be false, the loop will terminate and also the program will resume execution at the declare that instantly follows the loop. The figure below shows the logic of this loop.


*

*

In this example, the number change is referred to as the loop regulate variable because that controls the variety of times the the loop iterates. The if loop is well-known as a pretest loop, which method it tests its expression before each iteration.

Infinite Loops

Loops need to contain within themselves a method to terminate. This method that something inside the loop must ultimately make the test expression false. The loop in the example above stops as soon as the expression (number is false. If a loop go not have actually a way of stopping, the is dubbed an unlimited loop. One infinite loop continues to repeat until the program is interrupted. Right here is an example 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 value of the number variable. Every time the expression (number is tested, number will certainly contain the worth 0. That also feasible to develop an limitless loop by accidentally place a semicolon after ~ the very first line of the when loop.

int number = 0;while (number cout number++The semicolon in ~ the end of the an initial line is presume to be a null statement and disconnects the if statement indigenous the block the comes after ~ it. To the compiler, this loop watch like:

while (number This while loop will certainly forever execute the null statement, which does nothing. The regime will appear to have actually “gone into space” since there is nothing to display screen screen output or display activity.

The do-while Loop

The do-while loop watch something favor an inverted while loop. The figure below shows the logic of a do-while loop.


The do-while loop is a posttest loop. This means it does no test its expression until it has completed one iteration. As a result, the do-while loop constantly performs at least one iteration, also if the expression is false to start with. This differs from the habits of a while loop, which you will recall is a pretest loop.

The for Loop

In general, there room two categories of loops: conditional loops and also count-controlled loops. A conditional loop executes as long as a specific condition exists. For example, an input validation loop executes as lengthy as the input worth is invalid. As soon as you compose a conditional loop, you have actually no method of learning the number of times it will certainly iterate.

Sometimes you know the exact variety of iterations that a loop have to perform. A loop the repeats a specific number of times is well-known as a count-controlled loop. For example, if a loop asks the user to get in the sales quantities for each month in the year, it will iterate twelve times. In essence, the loop counts come twelve and asks the user to get in a sales amount each time it provides a count. A count-controlled loop should possess 3 elements:

It need to initialize a counter variable come a starting value.It should test the respond to variable by compare it to a preferably value. When the counter variable get its preferably value, the loop terminates.It have to update the counter variable throughout each iteration. This is generally done through incrementing the variable.

Count-controlled loops space so usual that C++ provides a kind of loop specifically for them. It is known as the because that loop. The for loop is particularly designed come initialize, test, and also update a counter variable. Here is the style of the because that loop when it is offered to repeat a block is:


The first line of the because that loop is the loop header. ~ the crucial word for, there are three expressions within the parentheses, be separate by semicolons. (Notice there is no a semi- colon after ~ the third expression.) The very first expression is the initialization expression. The is usually used to initialize a respond to variable come its beginning value. This is the an initial action perform by the loop, and also it is only done once. The second expression is the test expression. This is one expression that controls the execution of the loop. As long as this expression is true, the human body of the because that loop will repeat. The for loop is a pretest loop, for this reason it evaluate the check expression before each iteration. The third expression is the update expression. That executes in ~ the finish of every iteration. Typically, this is a statement the increments the loop’s counter variable.

Here is an example of a basic for loop the prints “Hello” five times:

for (int count = 0; counting cout In this loop, the initialization expression is counting = 0, the test expression is counting , and also the upgrade expression is count++. The body of the loop has actually one statement, i beg your pardon is the cout statement. Figure below illustrates the succession of events that takes place during the loop’s execution. Notice that steps 2 v 4 are repetitive as long as the check expression is true.


Notice how the respond to variable, count, is offered to regulate the variety of times that the loop iterates. During the execution that the loop, this change takes top top the values 1 v 5, and also when the test expression count is false, the loop terminates. Also notice that in this instance the count variable is provided only in the loop header, to manage the number of loop iterations. The is not supplied for any type of other purpose. It is also possible to use the respond to variable in ~ the body of the loop. Due to the fact that the for loop test its test expression prior to it performs one iteration, that is a pretest loop.

Deciding which Loop come Use

Each of the 3 C++ loops is appropriate to use in different situations. Here’s a short review 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 certain condition exists. The is additionally a pretest loop, so the is appropriate in situations where you execute not want the loop to iterate if the problem is false from the beginning. For example, validating intake that has been read and also reading list of data terminated by a sentinel worth are great applications the the if loop.The do-while loop. The do-while loop is additionally a conditional loop. Uneven the while loop, however, do-while is a posttest loop. The is appropriate in instances where you always want the loop come iterate at least once. The do-while loop is a good choice because that repeating a menu.The for loop. The for loop is a pretest loop the has built-in expressions because that initializing, testing, and updating. This expressions make it very convenient to use a respond to variable to control the variety of iterations that the loop performs. The initialization expression can initialize the counter variable come a starting value, the check expression have the right to test the respond to variable to determine whether it holds the preferably value, and the update expression have the right to increment the counter variable. The because that loop is right in cases where the exact number of iterations is known.Optional Topics: Breaking and also Continuing a Loop

Sometimes it’s crucial to avoid a loop before it goes through all that iterations. The break statement, which was offered with move in thing 4, can likewise be placed inside a loop. When it is encountered, the loop stops, and also the routine jumps to the statement instantly following the loop.

The when loop in the complying with program segment appears to execute 10 times, however the break statement reasons it to avoid after the fifth iteration.

int count = 0;while (count++ cout if (count == 5) break;Using break in a Nested Loop

In a nested loop, the rest statement only interrupts the loop that is inserted in. The following program segment displays five rows that asterisks top top the screen. The outer loop controls the number of rows, and the inside loop controls the number of asterisks in every row. The within loop is design to screen 20 asterisks, yet the break statement stops it throughout the eleventh iteration.

for (int heat = 0; row because that (int star = 0; star cout if (star == 10) break; cout The continue Statement

The proceed statement reasons the existing iteration the a loop to end immediately. When proceed is encountered, all the statements in the body of the loop that show up after it room ignored, and the loop prepares because that the following iteration.

See more: Watch Fairy Tail Episode 176 English Dubbed Full Episode 136

In a while loop, this means the routine jumps come the check expression at the optimal of the loop. Together usual, if the expression is tho true, the following iteration begins. In a do-while loop, the routine jumps come the check expression in ~ the bottom that the loop, which determines even if it is the next iteration will begin. In a for loop, continue reasons the upgrade expression to be executed and then the test expression to it is in evaluated.

The following program segment demonstrates the use of proceed in a while loop:

int testVal = 0;while (testVal++ if (testVal == 4) continue; cout This loop looks choose it displays the integers 1 v 10. When testVal is same to 4, however, the continue statement reasons the loop to skip the cout statement and begin the following iteration. The calculation of the loop is