Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Getting Familiar With Loops In C++

In this back to the basics tutorial, we’re going to be exploring loops in C++, something that you’ll take with you well into your software development career, regardless of programming language. The content in this tutorial is targeted at new developers or those that would like to start learning C++.

So when might you want to use a loop? If you need to perform a repetitive task of any kind, a loop is probably going to be want you want to use.

In this tutorial we’re going to explore for loops, while loops, and do-while loops using the C++ programming language.

If you need help configuring your development environment for C++, check out my previous tutorial titled, Configure Visual Studio Code for C++ Development, which demonstrates how.

Using the For Loop

The first type of loop we’ll explore, and one that I use probably more frequently than any other, is the for loop. With the for loop, you can define a starting point, and ending point, and a change value in the repetition cycle.

Take the following for example:

for (int i = 0; i < 10; i++) {
    cout << "For Counter Value: " << i << endl;
}

The above loop is constructed based on three parts separated by semicolon. Starting at an integer value of zero, the loop will increase by one, hence the i++, and continue until the integer value is ten or more. During every cycle of the loop, the counter value is printed to the screen.

Essentially the following would be printed:

For Counter Value: 0
For Counter Value: 1
For Counter Value: 2
For Counter Value: 3
For Counter Value: 4
For Counter Value: 5
For Counter Value: 6
For Counter Value: 7
For Counter Value: 8
For Counter Value: 9

Remember, that even though we have ten as our stopping point, we only ever print up until nine. This is because i < 10, not i <= 10.

The design of the for loop can be different than what we had just seen. For example, we could do the following instead:

for (int i = 0; i < 10; i+=2) {
    cout << "For Counter Value: " << i << endl;
}

Notice in the above example, we’re changing how the counter changes. Instead of increasing by one, we are now increasing by two. We could also change what value the loop starts at and what value it terminates on. The loop doesn’t even need to be using integer values. For example, if using an iterator, we could do something like this:

vector<int> v;
for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
    cout << *it << endl;
}

In the above example, we would iterate from the beginning of the vector to the end while increasing the iterator by one. In the above example our vector has no data in it, but you get the idea.

Let’s look at another example of a for loop:

int values[] = { 2, 4, 6, 8 };
int size = sizeof(values) / sizeof(*values);
for (int i = 0; i < size; i++) {
    cout << i << ": " << values[i] << endl;
}

In the above example we have an array of integer values. Rather than hard-coding the length of the array which we know to be four, we can programmatically calculate the size. The sizeof function will give us the size of the array, but size doesn’t always mean length. In the scenario of the integer, each element in the array can be up to four bytes in size, so an array with four values would return a size of sixteen. We can resolve this by simple division.

Using the calculated size, we can use it as the ending condition for the for loop.

The for loop can even be nested, likewise with every other loop. Take the following example:

for (int row = 0; row < 10; row++) {
    cout << row << ": ";
    for (int column = 0; column < 10; column++) {
        cout << column << " ";
    }
    cout << endl;
}

The above example might represent rows and columns. The goal is to have ten rows and every row has ten columns. The result might look like the following:

0: 0 1 2 3 4 5 6 7 8 9
1: 0 1 2 3 4 5 6 7 8 9
2: 0 1 2 3 4 5 6 7 8 9
3: 0 1 2 3 4 5 6 7 8 9
4: 0 1 2 3 4 5 6 7 8 9
5: 0 1 2 3 4 5 6 7 8 9
6: 0 1 2 3 4 5 6 7 8 9
7: 0 1 2 3 4 5 6 7 8 9
8: 0 1 2 3 4 5 6 7 8 9
9: 0 1 2 3 4 5 6 7 8 9

When nesting for loops, the outer loop will start based on the conditions of the loop. When the inner loop is reached, the outer loop will wait until the inner loop finishes, at which point the next cycle of the outer loop will start. The inner loop will be reset every time it is reached.

There are plenty of other for loop scenarios, but they all follow the same strategy.

Using the While Loop

The while loop is a little different than the for loop in the sense that there is only a stopping condition being checked for. You don’t define the starting logic or the change logic directly within the while loop parameter set.

Take the following example:

int i = 0;
while(i < 10) {
    cout << "While Counter Value: " << i << endl;
    i++;
}

The above example mimics our first for loop example. However, this time we’ve declared and initialized the counter value outside of the loop condition. Inside the loop, not the condition area, we increase the counter.

Just like with the for loop, we are flexible in what we can accomplish. Instead of counting forward, now we’ll try looping backwards:

int i = 10;
while(i > 0) {
    cout << "While Counter Value: " << i << endl;
    i--;
}

In the above example we start at ten and loop backwards until the counter is zero or less. In terms of results, we might have something like this:

While Counter Value: 10
While Counter Value: 9
While Counter Value: 8
While Counter Value: 7
While Counter Value: 6
While Counter Value: 5
While Counter Value: 4
While Counter Value: 3
While Counter Value: 2
While Counter Value: 1

We’re not printing zero because our loop ends at zero, hence the i > 0. If i >=0 was our condition, then zero would be inclusive.

Now let’s have a look at that rows and columns example from the for loop, but this time as a while loop:

int row = 0, column = 0;
while (row < 10) {
    cout << row << ": ";
    while (column < 10) {
        cout << column << " ";
        column++;
    }
    row++;
    column = 0;
    cout << endl;
}

Looping rows and columns with a while loop is a bit different. First we define our two counters. The outer loop will only increase the counter after the inner loop as finished. Because the inner loop doesn’t automatically reset like it does with a for loop, the counter must be reset when it finishes, otherwise the inner loop will never work again because the condition had been met.

Now let’s have a look at a do-while alternative.

Using the Do-While Loop

The do-while loop is similar to the while loop, however, at least one iteration will happen regardless of the loop condition.

Take the following for example:

int i = 0;
do {
    cout << "Do-While Counter Value: " << i << endl;
    i++;
} while(i < 10);

In the above example, we are initializing our counter at zero and looping until it is greater than or equal to ten. However, if we were to change our initial counter to twenty instead of zero, the loop will still print out the following:

Do-While Counter Value: 20

This is because the condition of the loop isn’t checked until after the code block is finished that first time. This is convenient if you want to accept user input and ask if they’d like to accomplish some kind of looping activity.

Conclusion

You just saw some examples of different loops in C++. Like I mentioned, this is a back to the basics tutorial, meaning the concepts here are good for new developers because it is skills that will be used for the rest of your career as a developer.

The best way to learn how to code is to write code, so it is a good idea to practice writing different looping scenarios in C++ or whatever other language you wish to use.

If you want to see a getting started with C++ example, check out my tutorial titled, Building a Hello World Example C++ Application.

A video version of this tutorial can be seen below.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.