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

C and C++ C++ Basics Loops in the C++ language (while, do while)

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
{
        // příkazy
} while ( /* podmínka */ );

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 ve 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, Arrays in the C++ language, we'll show you how to work with arrays. You've already learned quite a lot! Nothing better than a little noggin exercise, right? :)


 

 

Article has been written for you by David Capka
Avatar
Do you like this article?
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 College The author learned IT at the Unicorn College - a prestigious college providing education on IT and economics.
Thumbnail
Previous article
Loops in the C++ language
Thumbnail
All articles in this section
C++ basic constructs
Activities (3)

 

 

Comments

To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

No one has commented yet - be the first!