Please enable JavaScript to use CodeHS

Loops in C++

By David Burnham

Introduction

Loops are one of the fundamental coding blocks programmers use to help control the flow of the program. Some loops are designed so that a program will execute a series of steps multiple times, while others are designed to loop unitl a specific condition is met.

We will explore both of these basic loops in this tutorial.

For Loops

The first loop we will look at is the for loop. The for loop is typically used when we want to loop over a block of code a specific number of times. Let’s take a look at the different parts of the for loop call:

Notice the declaration has 3 parts to it. The first part, int i = 0, creates and initializes our loop variable. This variable can be used in our code block if needed. The second part checks the condition, in this case i < 5. As long as our loop variable is less than 5 at the start of our loop, our program will execute the entire code block. Finally, we see our incrementer, i++. This gets executed after each loop, but before the condition check. In this case, our loop variable i will get incremented by one each time we run the loop.

So how many times will this loop run? Try it out and see if you are correct!

Variations on the Basic For Loop

As we saw above, the basic for loop has three parts: a starting point, an ending point, and an increment each time. Typically, we start at zero, end at some specific number, and count up by 1. The for loop offers a lot of flexibility though. We can actually start and stop at any number and increment (or even decrement) with any interval.

Here are some example:

While Loops

Our for loops are perfect when we want to loop a specific number of times, but what if we don’t know how many times we need to loop? For example, if you want to ask users to enter quiz scores, you may not know how many they are going to enter. This is perfect for a while loop!

While loops use a conditional statement and the loop continues to execute while the condition is true. In the example above, a program can continue to prompt a user for score until they are done. If they have 2 scores or 200 scores, the program will continue to loop correctly.

Let’s look at a simple example below:

Your turn to try

Now it is your turn to try! Make a loop that will count by 5s starting at 5 until you reach 100. Which loop will you use? Can you write it as both a for loop and a while loop?