Lesson 6 - Loops in the C++ language

C and C++ C++ Basics Loops in the C++ language

In the previous tutorial, Conditions (branching) in the C++ language, we learned about conditions in the C++ language. In today's lesson, we're going to introduce you all to loops. After today's lesson, we'll have almost covered all of the basic constructs to be able to create reasonable applications.

Loops

The word loop suggests that something is going to repeat. When we want a program to do something 100 times, we certainly won't write the same code 100x. Instead, we'll put it in a loop. There are several types of loops. We'll explain how to use them, and of course, make practical examples.

The for loop

This loop has a determined fixed number of steps and contains a control variable, typically an integer, which changes values gradually during the loop. The for loop syntax is the following:

for (variable; condition; command)
  • variable is the control variable which is set to an initial value (usually 0, because in programming, everything starts from zero, never from one). For example: int i = 0. In the C++ language, we usually declare the variable directly in the loop and it's accessible only from inside the loop. Of course, you could declare the variable separately above the loop as well.
  • condition is the condition for executing the next step of the loop. Once it becomes false, the entire loop is terminated. The condition may be, for example, i < 10.
  • command tells us what will happen to our variable on every step, i.e. whether it will have increased or decreased. We use the special ++ and -- operators for this. Of course, you can use these operators outside the loop as well, they decrease or increase a variable by 1.

Let's create a simple example. Lots of us certainly know Sheldon from The Big Bang Theory. For those who don't, we'll simulate a situation where a guy knocks on his neighbor's door. He always knocks 3 times and then yells: "Penny!". Our code, without using a loop, would look like this:

cout << "Knock" << endl;
cout << "Knock" << endl;
cout << "Knock" << endl;
cout << "Penny!" << endl;
cin.get();

However, using loops, we no longer have to copy the same code over and over:

for (int i = 0; i < 3; i++)
{
        cout << "Knock" << endl;
}
cout << "Penny!" << endl;
cin.get();

Console application
Knock Knock Knock Penny!

The loop will run through 3 times. At the very beginning, i is set to zero, the loop then prints "Knock" and increases i by one. It continues in the same way with the values one and two. Once i hits three, the condition i < 3 is no longer true and the loop terminates. Loops have the same rules for omitting curly brackets as conditions. In this case, they may be omitted since the loop contains only one command. Now, we can simply change the value from 3 to 10 in the loop declaration. The command will then execute 10x without writing anything else. Surely, you can see that loops are a very powerful tool.

Now, let's put the variable incrementation to use. We'll print the numbers from one to ten and separate them with spaces. Since we want to write numbers next to each other, we'll write a space instead of endl this time:

for (int i = 1; i <= 10; i++)
        cout << i << " ";
cin.get();

We can see that the control variable has a different value after each iteration (an iteration is one step of the loop). Notice that this time, the loop doesn't start from zero because we want the initial value to be 1 and the last one to be 10. Just keep in mind that in programming, almost everything starts from zero, we'll find out why later.

Now, let's print a simple multiplication table that contains the product of numbers from 1 to 10. All we need to do is to declare a loop from 1 to 10 and multiply the control variable with the current multiplier. Our might look something like this:

cout << "Here's a simple multiplication table using loops: " << endl;
for (int i = 1; i <= 10; i++)
        cout << i << " ";
cout << endl;
for (int i = 1; i <= 10; i++)
        cout << i * 2 << " ";
cout << endl;
for (int i = 1; i <= 10; i++)
        cout << i * 3 << " ";
cout << endl;
for (int i = 1; i <= 10; i++)
        cout << i * 4 << " ";
cout << endl;
for (int i = 1; i <= 10; i++)
        cout << i * 5 << " ";
cout << endl;
for (int i = 1; i <= 10; i++)
        cout << i * 6 << " ";
cout << endl;
for (int i = 1; i <= 10; i++)
        cout << i * 7 << " ";
cout << endl;
for (int i = 1; i <= 10; i++)
        cout << i * 8 << " ";
cout << endl;
for (int i = 1; i <= 10; i++)
        cout << i * 9 << " ";
cout << endl;
for (int i = 1; i <= 10; i++)
        cout << i * 10 << " ";
cout << endl;
cin.get();

Console application
Simple multiplication table using loops: 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50 6 12 18 24 30 36 42 48 54 60 7 14 21 28 35 42 49 56 63 70 8 16 24 32 40 48 56 64 72 80 9 18 27 36 45 54 63 72 81 90 10 20 30 40 50 60 70 80 90 100

The program works nicely, but we still wrote a lot. Honestly, we could break it down even more since all it does is repeat 10 times while increasing the multiplier. What we'll do is nest the loops (put one inside the other):

cout << "Here's a simple multiplication table using nested loops: " << endl;
for (int j = 1; j <= 10; j++)
{
        for (int i = 1; i <= 10; i++)
                cout << i * j << " ";
        cout << endl;
}
cin.get();

Makes a big difference, doesn't it? Obviously, we can't use i in both loops since they are nested and would interfere with each other. The variable j of the outer loop goes through the values from 1 to 10. During each iteration of the loop, another inner loop with the variable i is executed. We already know that it'll write the multiples, in this case, it multiplies by the variable j. After each time the inner loop terminates it's necessary to break the line, which is done using cout << endl;.

Let's make one more program where we'll practice working with an outer variable. The application will be able to calculate raise an arbitrary number by an arbitrary exponent:

cout << "Exponent calculator" << endl;
cout << "===================" << endl;
cout << "Enter the base:" << endl;
int a, n; // we can declare both variables on a single line
cin >> a;
cout << "Enter the exponent:" << endl;
cin >> n;

int result = a;
for (int i = 0; i < (n - 1); i++)
        result = result * a;

cout << "Result: " << result << endl;
cout << "Thank you for using our exponent calculator";
cin.get(); cin.get();

I'm sure we all know how powers (exponents) work. However, just to be sure, let me remind you that, e.g. 23 = 2 * 2 * 2. So, we compute an by multiplying the number a by the number a n-1 times. Of course, the result must be stored in a variable. Initially, it'll have a value of a and this value will be gradually multiplied during the loop. We can see that our variable result in the loop body is accessible. If, however, we were to create a variable in a loop body, it would no longer be accessible after the loop terminates.

Console application
Exponent calculator =================== Enter the base: 2 Enter the exponent: 3 Result: 8 Thank you for using our exponent calculator

Now, we know what some practical uses of the for loop are. Remember that it has a fixed amount of iterations (there's no workaround for this). We shouldn't modify the control variable from inside the loop since the program could get stuck in an infinite loop. Here's the last example of what you should not do:

// this code is wrong
for (int i = 1; i <= 10; i++)
        i = 1;

Ouch, as you can clearly see, the program is stuck. The loop always increments the variable i, but it is always set back to 1. Meaning that it never reaches values > 10 and the loop never ends. We'll stop the program using the "Stop" button in the Visual Studio toolbar.

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 the following:

while (condition)
{
        // commands
}

If you 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. Typically, we call a method which returns the logical true/false value in the while loop's parentheses. We could rewrite the original for-loop example using the 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 he wishes to calculate another math problem. We'll remind you what the original code looked like (this is the version with the switch, but feel free to use the if-else version, it's up to you):

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", and we'll check the content of the variable goOn. This variable is set to "yes" in the beginning because the program has to begin somehow, then we 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();

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:

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. Certainly, this sort of loop will be executed at least once. As an example, 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 the 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 it there with do-while loops.

The do-while loop is not as common as the two loops mentioned before, however, it's handier in certain situations.

Our application can now be used multiple times and is almost complete. Note: this is one of the few codes that cannot be run online since our user bot would have to repeat inputs.

There are a few more things we can do with loops and you'll learn about them further along in the course. We don't think it's a good idea to overload you with so much syntax right from the start.

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? :)


 

  Activities (4)

Article has been written for you by David Capka
Avatar
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 Author learned IT at the Unicorn College - prestigious college providing IT and economical education.

Do you like this article?
Nobody has rated this just yet, be the first one!


 


Thumbnail
All articles in this section
C++ basic constructs

 

 

Comments

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

Nobody has commented yet - be the first!