Loops

What is a Loop?

A loop is a way for you to repeatedly run the same code for a specified amount of time. The most common use of loops is to look through each element in a list of items one by one, but they can be used in many different situations.

While Loop

In theory, a while loop is extremely easy to use. Going back to the idea of if statements, a while loop will continue running the code in the brackets as long as the expression it is given evaluates to true. As soon as the expression evaluates to false, the loop is exited. The catch here is that to properly use a while loop, the loop should have something in its code that will alter the result of the expression, otherwise, it will run infinitely and the program will crash.

An example of a while loop looks like:

while (alive == true) { // Code here... }

For Loop

The most commonly used loop by far is the for loop. The major advantage of a for loop is that in a single declaration, you can create a variable for your loop to use, provide an expression so your loop knows when to stop, and a command to be run after each iteration. The most common example of a for loop being used is

for (int i = 0; i < numbers.size(); i++) { // Code here... }

This creates a loop where i is every valid index in the vector “numbers”!

Range-Based For Loop

You will learn how exactly this works in 131 and beyond, but for now, consider this C++ magic bestowed upon us by the gods. If you understand Python well, then a C++ range-based for loop works exactly the same way that looping through an iterable object does there. If you do not know Python, do not worry.

Here is the syntax for a range-based for loop that loops through all the numbers in the array “numbers”

for (int x : numbers) { // Code here… }

What does this do for us? Well, for every element inside of numbers, we are extracting the value, putting it into x, and calling our loop code with the value stored in x. Then in the next iteration, it extracts the next value, and so on. It's magic!