Creating Loops in C++

Learn how we can use loops to iterate over a block of code, executing it as many times as needed.
This lesson is part of the course:

Intro to C++ Programming

Become a software engineer with C++. Starting from the basics, we guide you step by step along the way

3D art showing a dragon monster
Ryan McCombe
Ryan McCombe
Posted

So far, the code we have written has been able to create programs that execute a single stream of statements, and then exit.

In this lesson, we will learn about loops. Loops will allow us to repeatedly execute a block of code, until some condition within our program changes.

While Loops

The most basic form of loop is the while loop. It executes a block of code as long as a boolean expression remains true.

The basic structure of a while loop looks like this:

while (someBoolean) DoSomething();

Where we need to have multiple statements executed in our loop, we can wrap them with { and }, like in the following example:

while (someBoolean) {
  DoSomething();
  DoAnotherThing();
}

For example, to write the numbers from 1 to 10 to the console using a while loop, we could do this:

int Number { 1 };
while (Number <= 10) {
  cout << Number << endl;
  ++Number;
}

The syntax of a while loop is very similar to the if statements we have seen in the past. We have the keyword while, a boolean expression inside ( and ), and a statement to execute.

The main difference between an if and a while is that an if statement will execute once if the provided expression is true, whilst a while statement will execute continuously, as long as the provided expression remains true.

Iteration

Commonly, the way developers refer to loops is "iteration".

For example, "the i variable is increased on every iteration", or "we iteratively call the TakeDamage function".

If the condition provided to a while loop is false at the point the while loop attempts to start, the code inside the block is not executed - not even once.

The following code will not log out anything:

while (false) {
  cout << "Can't see me!" << endl;
}

Test your Knowledge

What will be the value of i after running this code?

int i { 0 };
while (i <= 5) {
  ++i;
}

Do While Loops in C++

A do while loop is very similar to a while loop, with two key differences. The first is that the syntax is slightly different - the condition comes at the end of the block:

do {
  // Body here
} while (shouldLoop);

To log out the numbers from 1-10 using a do while loop, we could do this:

int Number { 1 };
do {
  cout << Number << endl;
  ++Number;
} while (Number <= 10);

The second difference between a while and a do while is that the code inside the block of a do while loop will always be executed at least once, even if the boolean is false.

The following code will log out Hello World! one time.

do {
  cout << "Hello World!" << endl;
} while (false);

Test your Knowledge

What will be the value of i after running this code?

int i = 0;
do {
  i++;
} while (i < 0);

For Loops in C++

The third type of loop, the for loop, is slightly more complicated.

The basic structure is:

for  (initialise; condition; update) {
  // Code here
}

We have three components inside the ( and ) of the for loop. These are:

  • Initialise - this statement is executed a single time, before our loop starts
  • Condition - this is the boolean expression that indicates if our loop should continue
  • Update - this code is executed at the end of each loop iteration

These three components are separated by a semicolon ;

Lets see an example of how we can use this to log out the numbers from 1 to 10:

for (int Number { 1 }; Number <= 10; ++Number) {
  cout << Number << endl;
}

Test your Knowledge

What will be the value of Number after running this code?

int Number { 0 };
for (int i { 0 }; i < 10; ++i) {
  Number++;
};

With for loops, all three components inside the ( and ) are optional - we can omit the ones we don't need.

However, we still do need to keep the semicolons, to disambiguate which components we are using.

For example, to omit the 1st and 3rd component, we could do this:

int Number { 1 };
for ( ; Number < 10 ; ) {
  cout << Number << endl;
  ++Number;
}

The above is rather messy code. We should just use a while loop in that scenario, but it is possible to use a for loop. We can even remove the conditional check:

int Number { 1 };
for ( ; ; ) {
  cout << Number << endl;
  ++Number;
}

This code will compile, but you may see a problem with it. We're not specifying when the loop should stop, so the loop will never stop.

Infinite Loops

Inevitably, we will make a mistake when writing a loop that causes the loop to never end. For example:

int Number { 1 };
while (Number <= 10) {
  cout << Number << endl;
  // Oops!  we forgot to increment Number
}

Because the body of our loop is having no effect on the boolean expression that controls when our loop ends, this loop will not end under normal circumstances.

Number will always be <= 10. This is a fairly common scenario, called an infinite loop.

When we introduce an infinite loop, the remedy is usually just to force our program to close. For programs running in our terminal that are stuck in an infinite loop, we should still be able to close them from the title bar.

If that doesn't work, or we're creating a program that doesn't have the title bar, we can generally force our programs to close from our operating system - eg, ctrl + alt + delete in Windows, or Force Quit on Apple devices.

Nesting C++ Loops

The blocks created by our loop statements behave like any blocks we've seen, such as those associated with functions and if statements. They have their own scope, inside which we can create variables, call functions, and create other block statements.

For example, to log out the numbers from 1-10, but to treat one number differently, we could nest an if statement inside our loop:

int Number { 1 };
while (Number <= 10) {
  if (Number == 5) {
    cout << "Five!" << endl;
  } else {
    cout << Number << endl;
  }
  ++Number;
}

We can also nest loops within loops. For example:

for (int i = 0; i < 40; i+=20) {
  for (int j = 10; j <= 30; j++) {
    cout << i + j << " ";
  }
  cout << endl;
}

In the above example, we have an inner loop that logs out 20 numbers, with a space after each one. We then have an outer loop that calls that inner loop twice, and logs out a new line each time.

A photo of the numbers 10 to 50 logged out in a terminal window

In the next lesson, covering the modulus operator, we will see a slightly simpler way of implementing this behavior.

There is nothing special about the use of the variable names i and j. There is just a general convention that, if a better variable name is not available, we use the name i for the integer that controls the iteration count of loops. If i is not available, developers will often use j instead.

The continue Statement in C++ Loops

We can use the continue keyword within the body of a loop to give us more control over its execution. When we call continue, the loop will skip over the remaining code for this iteration, and continue onwards to the next.

If the condition that controls the loop is no longer true, the loop will instead end.

The continue word is most typically used in a conditional block within our loop. For example, to log the numbers from 1-10, whilst skipping over 5, we could write this code:

int Number { 0 };
while (Number < 10) {
  ++Number;
  if (Number == 5) continue;
  cout << Number << endl;
}

Test your Knowledge

What will be the value of Number after running this code?

int Number { 0 };
for (int i = 0; i < 10; i++) {
  if (i == 5) continue;
  Number++;
};

The break Statement in C++ Loops

The break keyword can be called within the body of a loop, in order to exit the loop entirely, and to stop iterating. Similar to how continue was used, break is generally most useful within a conditional in our loop.

For example, to limit the iterations of a while loop to 100, regardless of whether the condition is true, we could do this:

int RemainingIterations { 100 };

while (true) {
  DoSomething();

  --RemainingIterations;
  if (RemainingIterations <= 0) break;
}

The previous code demonstrates a pretty common technique for designing functions. This is especially useful when we don't know when the loop will end - for example, it might continue until the user presses a button.

Often, we will solve these problems by intentionally creating an infinite loop. We can do this by using a boolean expression that will always be true, such as the literal value true:

while (true) {
  doWork();
}

Then we can call break from within the loop when we want it to end. This gives us an easy way of implementing some additional behaviour before the loop ends:

while (true) {
  doWork();
  if (isComplete) {
    cout << "Task Complete!";
    break;
  }
}

Test your Knowledge

What will be the value of Number after running this code?

int i { 0 };
while (i >= 0) {
  if (i == 5) break;
  i++;
};

Returning from Loops

Within a loop, we can also use a return statement. This will break from the loop, but also return from the function where the loop was running.

In this example, we show an implication of this:

int main() {
  while (true) {
    // Close program if user pressed quit
    if (didUserPressExitButton()) return 0;

    // Otherwise, continue running
    RenderFrame();
  }
  SayGoodbye();
}

In the above function, SayGoodbye() will never be called. This highlights a subtle difference between return and break when used in the body of a loop. break will leave the loop - return will leave both the loop and the function.

This means that, if our function has some additional code that we always want to run after the loop ends, we should use break instead.

int main() {
  while (true) {
    // Close program if user pressed quit
    if (didUserPressExitButton()) break;

    // Otherwise, continue running
    RenderFrame();
  }
  SayGoodbye();
}

Was this lesson useful?

Ryan McCombe
Ryan McCombe
Posted
This lesson is part of the course:

Intro to C++ Programming

Become a software engineer with C++. Starting from the basics, we guide you step by step along the way

3D art showing a progammer setting up a development environment
This lesson is part of the course:

Intro to C++ Programming

Become a software engineer with C++. Starting from the basics, we guide you step by step along the way

Free, unlimited access!

This course includes:

  • 66 Lessons
  • Over 200 Quiz Questions
  • Capstone Project
  • Regularly Updated
  • Help and FAQ
Next Lesson

The Modulus (%) Operator in C++

Learn how we can use the modulus operator to get the "remainder" of integer division, and some common use cases.
3D art showing two RPG characters
Contact|Privacy Policy|Terms of Use
Copyright © 2023 - All Rights Reserved