The do-while loop is a pretest loop

The do-while loop looks something like an inverted while loop. The do-while loop is a posttest loop, which means its expression is tested after each iteration.

The do-while loop syntax

1. Here is the format of the do-while loop when it is used to repeat a single statement:

do
        statement;
  while(expression);

2. Here is the format of the while loop when it is used to repeat a block:

do
  {
        statement;
        statement;
        //place as many statements here as necessary
  }   while(expression);

  • ★ The do-while loop must be terminated with a semiconlon.
  • ★ Loops always executes at least once.
  • ★ Execution continues as long as expression is true, stops repetition when expression become false.
  • ★ Usefule in menu-driven programs to bring user back to menu to make another choice


Example

The do-while loop is a pretest loop

do-whileExample.cpp

The do-while Loop is a Posttest Loop

  • ★ The do-while loop is a posttest loop. This means it does not test its expression until it has completed an iteration.
  • ★ As a result, the do-while loop always performs at least one iteration, even if the expression is false to begin with.

Practice Program

1. Write a do-while loop to read a deposit amount from the user, the valid deposit amount needs to be between 0 and 5000. It continues to prompt the user until a valid deposit amount is read.

2. Wrtie a do-while loop to prompt the user to read an upper-case letter. It continues to prompt until an upper-case letter is entered.

In previous post, we went over the concept of control structures, which direct the flow of a program. A loop is a control structure that causes a statement or group of statements to repeat. C++ has three looping control structures: the while loop, the do-while loop, and the for loop. The difference between these structures is how they control the repetition.

The while Loop

The while loop has two important parts: (1) an expression that is tested for a true or false value, and (2) a statement or block that is repeated as long as the expression is true. The figure below shows the logic of a while loop.

Here is the general structure of the while loop:

In the general format, (expression)is any expression that can be evaluated as true or false, and statement;is any valid C++ statement. The first line shown in the figure above is called the loop header. It consists of the key word while followed by an expression enclosed in parentheses. Here’s how the loop works: the (expression)is tested, and if it is true, the statement(s) are executed. Then, the (expression)is tested again. If it is true, the statement(s) areexecuted. This cycle repeats until the (expression)is false. The statement(s) that is repeated is known as the body of the loop. The while loop works like an if statement that executes over and over. As long as the expression inside the parentheses is true, the body of the loop will repeat. The program below uses the while loop to print “Hello” five times.

// This program demonstrates a simple while loop.
#include <iostream>
using namespace std;
int main()
{
int number = 0;
while (number < 5)
{
cout << "Hello\n";
number++;
}
cout << "That's all!\n";
return 0;
}

This program tests the variable number to determine whether it is less than 5. If it is, then the statements in the body of the loop are executed. The statement number++; in the body of the loop uses the increment operator to add one to number. This is the last statement in the body of the loop, so after it executes, the loop starts over. It tests the expression (number < 5) again, and if it is true, the statements in the body of the loop are executed again. This cycle repeats until the expression (number < 5) is false. Each repetition of a loop is known as an iteration. This loop will perform five iterations because the variable number is initialized with the value 0, and it is incremented each time the body of the loop is executed. When the expression (number < 5) is tested and found to be false, the loop will terminate and the program will resume execution at the statement that immediately follows the loop. The figure below shows the logic of this loop.

In this example, the number variable is referred to as the loop control variable because it controls the number of times that the loop iterates. The while loop is known as a pretest loop, which means it tests its expression before each iteration.

Infinite Loops

Loops must contain within themselves a way to terminate. This means that something inside the loop must eventually make the test expression false. The loop in the example above stops when the expression (number < 5) is false. If a loop does not have a way of stopping, it is called an infinite loop. An infinite loop continues to repeat until the program is interrupted. Here is an example of an infinite loop:

int number = 0;
while (number < 5)
{
cout << "Hello\n";
}

This is an infinite loop because it does not contain a statement that changes the value of the number variable. Each time the expression (number < 5) is tested, number will contain the value 0. It’s also possible to create an infinite loop by accidentally placing a semicolon after the first line of the while loop.

int number = 0;
while (number < 5)
{
cout << "Hello\n"; // This semicolon is an ERROR!
number++
}

The semicolon at the end of the first line is assumed to be a null statement and disconnects the while statement from the block that comes after it. To the compiler, this loop looks like:

while (number < 5);

This while loop will forever execute the null statement, which does nothing. The program will appear to have “gone into space” because there is nothing to display screen output or show activity.

The do-while Loop

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

Here is the do-while loop’s structure when the body of the loop contains multiple statements:

The do-while loop is a posttest loop. This means it does not test its expression until it has completed an iteration. As a result, the do-while loop always performs at least one iteration, even if the expression is false to begin with. This differs from the behavior of a while loop, which you will recall is a pretest loop.

The for Loop

In general, there are two categories of loops: conditional loops and count-controlled loops. A conditional loop executes as long as a particular condition exists. For example, an input validation loop executes as long as the input value is invalid. When you write a conditional loop, you have no way of knowing the number of times it will iterate.

Sometimes you know the exact number of iterations that a loop must perform. A loop that repeats a specific number of times is known as a count-controlled loop. For example, if a loop asks the user to enter the sales amounts for each month in the year, it will iterate twelve times. In essence, the loop counts to twelve and asks the user to enter a sales amount each time it makes a count. A count-controlled loop must possess three elements:

  1. It must initialize a counter variable to a starting value.
  2. It must test the counter variable by comparing it to a maximum value. When the counter variable reaches its maximum value, the loop terminates.
  3. It must update the counter variable during each iteration. This is usually done by incrementing the variable.

Count-controlled loops are so common that C++ provides a type of loop specifically for them. It is known as the for loop. The for loop is specifically designed to initialize, test, and update a counter variable. Here is the format of the for loop when it is used to repeat a block is:

The first line of the for loop is the loop header. After the key word for, there are three expressions inside the parentheses, separated by semicolons. (Notice there is not a semi- colon after the third expression.) The first expression is the initialization expression. It is normally used to initialize a counter variable to its starting value. This is the first action performed by the loop, and it is only done once. The second expression is the test expression. This is an expression that controls the execution of the loop. As long as this expression is true, the body of the for loop will repeat. The for loop is a pretest loop, so it evaluates the test expression before each iteration. The third expression is the update expression. It executes at the end of each iteration. Typically, this is a statement that increments the loop’s counter variable.

Here is an example of a simple for loop that prints “Hello” five times:

for (int count = 0; count < 5; count++)
{
cout << "Hello" << endl;
}

In this loop, the initialization expression is count = 0, the test expression is count < 5, and the update expression is count++. The body of the loop has one statement, which is the cout statement. Figure below illustrates the sequence of events that takes place during the loop’s execution. Notice that Steps 2 through 4 are repeated as long as the test expression is true.

Notice how the counter variable, count, is used to control the number of times that the loop iterates. During the execution of the loop, this variable takes on the values 1 through 5, and when the test expression count < 5 is false, the loop terminates. Also notice that in this example the count variable is used only in the loop header, to control the number of loop iterations. It is not used for any other purpose. It is also possible to use the counter variable within the body of the loop. Because the for loop tests its test expression before it performs an iteration, it is a pretest loop.

Deciding Which Loop to Use

Each of the three C++ loops is ideal to use in different situations. Here’s a short summary of when each loop should be used.

  • The while loop. The while loop is a conditional loop, which means it repeats as long as a particular condition exists. It is also a pretest loop, so it is ideal in situations where you do not want the loop to iterate if the condition is false from the beginning. For example, validating input that has been read and reading lists of data terminated by a sentinel value are good applications of the while loop.
  • The do-while loop. The do-while loop is also a conditional loop. Unlike the while loop, however, do-while is a posttest loop. It is ideal in situations where you always want the loop to iterate at 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 for initializing, testing, and updating. These expressions make it very convenient to use a counter variable to control the number of iterations that the loop performs. The initialization expression can initialize the counter variable to a starting value, the test expression can test the counter variable to determine whether it holds the maximum value, and the update expression can increment the counter variable. The for loop is ideal in situations where the exact number of iterations is known.

Optional Topics: Breaking and Continuing a Loop

Sometimes it’s necessary to stop a loop before it goes through all its iterations. The break statement, which was used with switch in Chapter 4, can also be placed inside a loop. When it is encountered, the loop stops, and the program jumps to the statement immediately following the loop.

The while loop in the following program segment appears to execute 10 times, but the break statement causes it to stop after the fifth iteration.

int count = 0;
while (count++ < 10)
{
cout << count << endl;
if (count == 5)
break;
}

Using break in a Nested Loop

In a nested loop, the break statement only interrupts the loop it is placed in. The following program segment displays five rows of asterisks on the screen. The outer loop controls the number of rows, and the inner loop controls the number of asterisks in each row. The inner loop is designed to display 20 asterisks, but the break statement stops it during the eleventh iteration.

for (int row = 0; row < 5; row++) 
{
for (int star = 0; star < 20; star++)
{
cout << ‘*’;
if (star == 10)
break;
}
cout << endl;
}

The continue Statement

The continue statement causes the current iteration of a loop to end immediately. When continue is encountered, all the statements in the body of the loop that appear after it are ignored, and the loop prepares for the next iteration.

In a while loop, this means the program jumps to the test expression at the top of the loop. As usual, if the expression is still true, the next iteration begins. In a do-while loop, the program jumps to the test expression at the bottom of the loop, which determines whether the next iteration will begin. In a for loop, continue causes the update expression to be executed and then the test expression to be evaluated.

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

int testVal = 0;
while (testVal++ < 10)
{
if (testVal == 4)
continue;
cout << testVal << “ “;
}

This loop looks like it displays the integers 1 through 10. When testVal is equal to 4, however, the continue statement causes the loop to skip the cout statement and begin the next iteration. The output of the loop is

1 2 3 5 6 7 8 9 10

What type of loop is the do

The do-while loop is a posttest loop, which means its expression is tested after each iteration.

Do While is a posttest loop?

Do while loops check the condition after the block of code is executed. This control structure can be known as a post-test loop. This means the do-while loop is an exit-condition loop. However a while loop will test the condition before the code within the block is executed.

What are the pretest loops?

pretest loop: A loop that tests the condition before each iteration. posttest loop: A loop that tests the condition after each iteration.

Is a do

The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.