Get up to 80 % extra points for free! More info:

Lesson 7 - Loops in the C++ language (while, do while)

Lesson highlights

Are you looking for a quick reference on the while loop and advanced loop syntax in C++ instead of a thorough-full lesson? Here it is:

Using a while loop when we don't know how many times the code is going to repeat:

cout << "Welcome to our calculator" << endl;
string goOn = "yes";
while (goOn == "yes")
{
    cout << "Enter the first number:" << endl;
    double a;
    cin >> a;
    cout << "Enter the second number:" << endl;
    double b;
    cin >> b;
    cout << "Choose one of the following operations:" << endl;
    cout << "1 - addition" << endl;
    cout << "2 - subtraction" << endl;
    cout << "3 - multiplication" << endl;
    cout << "4 - division" << endl;
    int option;
    cin >> option;
    double result = 0.0;
    switch (option)
    {
        case 1:
            result = a + b;
            break;
        case 2:
            result = a - b;
            break;
        case 3:
            result = a * b;
            break;
        case 4:
            result = a / b;
            break;
    }
    if ((option > 0) && (option < 5))
        cout << "Result: " << result << endl;
    else
        cout << "Invalid option" << endl;
    cout << "Would you like to make another calculation? [yes/no]" << endl;
        cin >> goOn;
}
cout << "Thank you for using our calculator. Press any key to end the program." << endl;
cin.get(); cin.get();

Using the do-while loop when the code is always executed at least once:

int a;
do
{
    cin >> a; // executed once and then only when the condition remains true
} while (a <= 2); // ends once the user enters 3 or larger

break exists the loop immediately:

int i;
for (i = 0; i < 20; i++)
{
    if (i * i > 130)
        break;
}
// i == 12
cout << i;

continue only skips the current loop iteration:

int i, a;
for (i = 2, a = 1; i < 10; i++)
{
    if (i % 3 == 0) // if the iteration index is divisible by 3
        continue; // skip
    cout << i << endl;
}

Would you like to learn more? A complete lesson on this topic follows.

In the previous lesson, Loops in the C++ language, we started learning about loops. In today's C++ tutorial, we're going to continue learning about them. We'll introduce you all to the while and do while loops.

The while loop

The while loop works differently. It simply repeats the commands in the block while the condition is true. The syntax of the loop is as follows:

while (condition)
{
    // commands
}

If you've realized that the for loop can be simulated using the while loop, you are absolutely right :) FOR is actually a special kind of while loop. However, the while loop is used for slightly different things. Simply put, it's a method which returns the logical true/false value from its parentheses. We could rewrite the original for-loop example using a while loop like this:

int i = 1;
while (i <= 10)
{
    cout << i << " ";
    i++;
}
cin.get();

However, this is not an ideal example of using the while loop. Let's take our calculator from the previous lessons and improve it a little bit. We'll add the ability to enter more math problems. The program will not end immediately, instead, it'll ask the user whether they wish to calculate another math problem. Here's where we left off (this is the version with the switch, but feel free to use the if-else version):

cout << "Welcome to our calculator" << endl;
cout << "Enter the first number:" << endl;
double a;
cin >> a;
cout << "Enter the second number:" << endl;
double b;
cin >> b;
cout << "Choose one of the following operations:" << endl;
cout << "1 - addition" << endl;
cout << "2 - subtraction" << endl;
cout << "3 - multiplication" << endl;
cout << "4 - division" << endl;
int option;
cin >> option;
double result = 0.0;
switch (option)
{
    case 1:
        result = a + b;
        break;
    case 2:
        result = a - b;
        break;
    case 3:
        result = a * b;
        break;
    case 4:
        result = a / b;
        break;
}
if ((option > 0) && (option < 5))
    cout << "Result: " << result << endl;
else
    cout << "Invalid option" << endl;
cout << "Thank you for using our calculator. Press any key to end the program." << endl;
cin.get(); cin.get();

Now, we'll put almost all of the code into a while loop. Our condition will be that the user has entered "yes", which we'll store within the variable goOn. This variable is set to "yes" in the beginning, otherwise, the program wouldn't be able to start. Then, we'll assign the user's choice to it:

cout << "Welcome to our calculator" << endl;
string goOn = "yes";
while (goOn == "yes")
{
    cout << "Enter the first number:" << endl;
    double a;
    cin >> a;
    cout << "Enter the second number:" << endl;
    double b;
    cin >> b;
    cout << "Choose one of the following operations:" << endl;
    cout << "1 - addition" << endl;
    cout << "2 - subtraction" << endl;
    cout << "3 - multiplication" << endl;
    cout << "4 - division" << endl;
    int option;
    cin >> option;
    double result = 0.0;
    switch (option)
    {
        case 1:
            result = a + b;
            break;
        case 2:
            result = a - b;
            break;
        case 3:
            result = a * b;
            break;
        case 4:
            result = a / b;
            break;
    }
    if ((option > 0) && (option < 5))
        cout << "Result: " << result << endl;
    else
        cout << "Invalid option" << endl;
    cout << "Would you like to make another calculation? [yes/no]" << endl;
        cin >> goOn;
}
cout << "Thank you for using our calculator. Press any key to end the program." << endl;
cin.get(); cin.get();

The result:

Console application
Welcome to our calculator
Enter the first number:
12
Enter the second number:
128
Choose one of the following operations:
1 - addition
2 - subtraction
3 - multiplication
4 - division
1
Result: 140.000000
Would you like to make another calculation? [yes/no]
yes
Enter the first number
-10.5
Enter the second number:

Our application can now be used multiple times in a row.

The do-while loop

The last loop type is do-while. It's almost identical to while, however, the control condition is placed at the end of the loop. It goes without saying that this sort of loop will be executed at least once. To demonstrate its abilities, we'll alter our calculator once more to use the do-while loop. Notice that it's no longer necessary to initialize the value of the goOn variable before the loop since the variable is set in the loop.

cout << "Welcome to our calculator" << endl;
string goOn; // We don't have to initialize its value anymore
do
{
    cout << "Enter the first number:" << endl;
    double a;
    cin >> a;
    cout << "Enter the second number:" << endl;
    double b;
    cin >> b;
    cout << "Choose one of the following operations:" << endl;
    cout << "1 - addition" << endl;
    cout << "2 - subtraction" << endl;
    cout << "3 - multiplication" << endl;
    cout << "4 - division" << endl;
    int option;
    cin >> option;
    double result = 0.0;
    switch (option)
    {
        case 1:
            result = a + b;
            break;
        case 2:
            result = a - b;
            break;
        case 3:
            result = a * b;
            break;
        case 4:
            result = a / b;
            break;
    }
    if ((option > 0) && (option < 5))
        cout << "Result: " << result << endl;
    else
        cout << "Invalid option" << endl;
    cout << "Would you like to make another calculation? [yes/no]" << endl;
        cin >> goOn;
} while (goOn == "yes");
cout << "Thank you for using our calculator. Press any key to end the program." << endl;
cin.get(); cin.get();

Notice the semicolon after the parentheses, we have to write add it in when using do-while loops.

The general syntax of the do-while loop is the following:

do
{
    // commands
} while ( /* condition */ );

We can use do-while for things such as reading inputs from the console. Consider that we wanted the user to enter a number greater than 2. However, what if they entered an invalid number? It's definitely not ideal to terminate the application after a single attempt. We'd be better off asking over and over until they enter a valid input. Here's what it would look like using a while loop:

int a;
cin >> a;
while (a <= 2)
{
    cin >> a;
}

Now, using a do-while loop:

int a;
do
{
    cin >> a;
} while (a <= 2);

Note: We'll learn even how to sanitize blank inputs further along the road.

It doesn't make a huge difference here. However, if we had a code longer than cin >> a;, we'd have to write it in twice if we were using simple while loops.

You may be wondering if we can come up with a similar shorter version using while, which holds true in this case:

int a = 1;
while (a <= 2)
{
    cin >> a;
}

However, the condition won't always be this simple.

Break and continue

The last thing we're going to add on to the loops is the break and continue commands.

The break command exits the current loop immediately.

int i;
for (i = 0; i < 20; i++)
{
    if (i * i > 130)
        break;
}
// i == 12
cout << i;

We've already seen the break command when we looked at switches. They work the exact same here - they exit the loop (switch). Break doesn't exit nested loops, it only exists within the current level.

On the other hand, continue only skips the current loop iteration, so that the rest of the iterations are executed normally.

int i, a;
for (i = 2, a = 1; i < 10; i++)
{
    if (i % 3 == 0)
        continue;
    a *= i;
}
// the result will be 2240 because we're doing the following: 1 * 2 * 4 * 5 * 7 * 8
cout << a;

The code above checks whether i is divisible by 3 and if so, the rest of the loop's body is skipped.

We have now covered everything you need to know about loops, for now.

In the next lesson, Solved tasks for C++ lessons 6-7, we'll show you how to work with arrays. You've already learned quite a lot! Nothing better than a little noggin exercise, right? :)

In the following exercise, Solved tasks for C++ lessons 6-7, we're gonna practice our knowledge from previous lessons.


 

Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.

Download

By downloading the following file, you agree to the license terms

Downloaded 5x (349.82 kB)
Application includes source codes in language C++

 

Previous article
Loops in the C++ language
All articles in this section
C++ Basic Constructs
Skip article
(not recommended)
Solved tasks for C++ lessons 6-7
Article has been written for you by David Capka Hartinger
Avatar
User rating:
No one has rated this quite yet, be the first one!
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn university David learned IT at the Unicorn University - a prestigious college providing education on IT and economics.
Activities