Select Page

Like most programming languages, C++ provides built-in tools that allow developers to examine and repeat operations on each element in an array until a condition has been met.

 In this article, we’ll introduce three types of C++ loops, go over use cases for each and touch on scenarios in which you might want to avoid using loops in C++.

Which Loops Are Available in C++?

All C++ loops let us iterate over several elements — be it indexes in an array of raw values — and call a function or execute a series of operations with each element. That said, C++ developers have various types of loops at their disposal, and one will likely be better suited than another depending on the circumstances.

The For-Loop

Of all loops, the for-loop is the most widely known and used. The compiler loops through a code block containing a statement (or multiple statements) a certain number of times based on the loop’s conditional, incrementing or decrementing with every pass of the loop. Since it checks if the condition is true before executing the loop’s code block, it will not run if that condition is not met. 

The While Loop

Another widely used type of loop is the while loop. Like the for-loop, it loops through a set of instructions as long as a given condition is met, testing the condition before executing the loop body. The major difference between a for-loop and while loop is how they are invoked: A for-loop contains three statements when declared (variable, condition and increment/decrement), whereas the invocation of a while loop contains only the conditional, with the variable and the increment/decrement addressed elsewhere.

The Do-While Loop

The syntax we use in a do-while loop is very similar to that in while loops, the difference being that do-while loops test the condition at the end of the loop structure. This means that a do-while loop will run at least once, even if the applicable condition is not met.

How To Use C++ Loops

To gain a better understanding of the above loops, let’s explore some example code for implementing each of the three.

The For-Loop

The for-loop’s three building blocks consist of an iterator followed by a condition that must be met for the loop block to run, and then an increment defining how the iterator should increase or decrease. 

In the following code, i is the iterator — the variable that will be increased (or decreased) with each pass of the loop. For the for loop to run, the condition that must be met is  i <= n, and the iterating statement is i++, which means that every time the loop’s code block runs, i increases by 1. (We could also write i + 1.) Here we declare the iterator i before the for-loop, but we can just as well declare the iterator and initialize it to zero inside the for-loop:

The code block itself can of course include a wide variety of statements. In this example, we simply printed the word “Count:” followed by the value of i from the current pass. The loop terminates when i reaches 6 because, at that point, i <= 5 proves false.

The While Loop

Unlike the for-loop, the while loop contains just one component inside the parentheses following the while keyword: a conditional that evaluates to true or false and determines whether the loop will run. Let’s say we want the same conditional as the for-loop above, that is, that the iterator must be 5 or less for the loop to run. In this case, we’ll write this conditional as while (i < 6). 

Even though the initialization and increment/decrement statements are missing from the parentheses, they are just as essential in the while loop as they are in the for-loop. We must initialize the incrementing variable i before the while loop begins, and the increment/decrement should happen within the loop’s code block:

#include <iostream>
using namespace std;

Look closely at the above code. When would our loop stop running? The answer is never! This is because we are decrementing i with each pass, and the condition declares that the code will run as long as i < 6. This creates an infinite loop. Infinite loops happen when we forget to increment or decrement our code in the body of a while loop, so take care to include logic that will eventually make the conditional statement return false and terminate the loop.

So, how do we fix this to obtain the same output as the for-loop? One approach would be to adjust the iterator to initialize at 0, then increment instead of decrement:

We can alternately keep the decrement and change the conditional so that i must always be a positive integer:

This will give us the same output as the for-loop, but in reverse order (starting at 5 and ending at 0). 

The Do-While Loop

Lastly, let’s go over the do-while loop. As you may surmise from its name, this loop is very similar to the while loop but with one key difference: The conditional is evaluated after the statement block, not before it. 

Staying with our counting example, here’s what we would have:

This would yield exactly the same output as our regular while loop — except under one circumstance. If we change our condition to while (i < 0), our output will be Count: 0. This is because the compiler evaluates the conditional only after our statement runs. If the condition is false, it moves to the next line of code. If true, it loops through the do statement again.  

In the next few sections, we’ll explore when to use these loops and when not to use them.

When To Use Loops in C++

In the above examples, we printed out a count on each pass of a loop. Other use cases for loops include adding a number to an ever-growing sum variable with each iteration, or in a broader sense, changing any other variable in some way. Here’s what that might look like:

Our sum will print 10, the cumulative of every i added together, after the for loop ends.

In all these examples, we need to do something every time the loop runs. Anything that persists after the code block runs is referred to as a side effect, so a common use case for loops is precisely whenever we would require such a side effect.

Another common use case for C++ loops is when you need to wait until something happens. For example, if you’re waiting for user input or network packets, you might use a loop that runs until that condition is met. 

When to Avoid Using Loops in C++

Like many other languages, C++ contains functions like map and reduce that can iterate over arrays, performing some functionality on each element. In cases where, for example, we need to aggregate data from an array or a vector, it’s better to use these other tools instead of resorting to looping. This increases program readability and reduces the potential for error.

Another instance in which loops can and should be avoided is when you have a higher-level function available. For example, we can read a string using std::getline rather than looping over the string, gathering the input word by word or character by character.

Nested and Infinite loops in C++

Finally, let’s look at some advanced use cases for loops in C++. You might have seen references to nested loops and wonder what they are. Nested loops are loops inside of loops; they are not only possible but quite common. 

Here’s how a nested loop might look:

While this isn’t a practical example, it shows you how nested looping works. Try it and see what output you get!

It’s also possible to combine different loops. For example, a do-while loop can be nested inside a for-loop, and a for-loop can be nested inside a while loop. Nested loops can be messy to look at, so if you do need to use different types of loops when nesting, we recommend keeping things as clean as possible. 

While using nested loops might seem convenient, the practice is best avoided where possible, in the name of good programming principles. If there’s a function in the standard library that does what you need, implementing a solution from scratch is counterproductive. 

Also, making use of the more robust code from standard libraries can result in more stable programs; their functions are battle-tested in different scenarios, including not-so-obvious edge cases.

Lastly, when employing two indices with conditions, it’s crucial to explain the purpose of each index to allow other people to read and understand your code. Code tends to be more readable when you use convenience functions.

Take the Next Step

We trust this article gave you valuable insight into how C++ developers use loops. If you already have a programming base, consider sharpening your C++ skills through our expert-taught C++ Nanodegree program. You’ll complete five real-world projects and get personalized feedback to set yourself up for success in the job market.  

Start Learning