Loops

Using conditionals, we could choose whether or not certain code should run. Now, with loops, we can also control how many times code can run. If there’s a certain piece of code that needs to be run multiple times, it’s much easier to put it in a “loop” than to copy and paste it many times.

While Loops

Using a while loop in the code below, we’re able to print every number from 0 to 100 out to the screen:

#include <iostream>

int main() {
    int numberToPrint = 0;
    while (numberToPrint <= 100) {
        std::cout << numberToPrint << "\n";
        numberToPrint++;
    }
    return 0;
}

You may notice that a while loop is structured very similarly to an if statement. Any condition (something with a true or false value) goes in the parentheses after the word “while.” Then, the code in the following curly braces is repeated “while” that condition is true. In this case, every time the code inside the while loop is run, the numberToPrint variable is increased by 1. When numberToPrint becomes a number that is greater than 100, however, the loop ends.

For Loops

For loops look a little different from while loops, but they work very similarly. Here’s code that does the same thing as above, using a for loop instead:

#include <iostream>

int main() {
    for (int numberToPrint = 0; numberToPrint <= 100; numberToPrint++) {
        std::cout << numberToPrint << "\n";
    }
    return 0;
}

You can see that there are three different statements (separated by semicolons) that go inside a for loop’s parentheses:

  • The first statement is only run one time (when the loop starts). It’s where you would often create a variable to be used within the loop (numberToPrint in this case).
  • The second statement is the same as what would go inside a while loop’s parentheses. The for loop stops when this condition becomes false.
  • The third statement is run every time after the code inside the for loop is run. Like the above code using the while loop, we increase the numberToPrint by 1 every time.

If we wanted to print every other number from 0 to 100, we could simply change numberToPrint++ to numberToPrint += 2:

#include <iostream>

int main() {
    for (int numberToPrint = 0; numberToPrint <= 100; numberToPrint += 2) {
        std::cout << numberToPrint << "\n";
    }
    return 0;
}

Most of the time, for loops you see will use the letter “i” for their variable name. This is only done because it’s a little easier to write, and it’s usually just as clear:

#include <iostream>

int main() {
    for (int i = 0; i <= 100; i += 2) {
        std::cout << i << "\n";
    }
    return 0;
}

Nested Loops

For loops and while loops can also be placed inside other for loops and while loops. This causes the “inner” loop to repeat until finishing every time the outer loop is repeated. Try to predict what the code below would do:

#include <iostream>

int main() {
    for (int i = 0; i < 10; i++) {
        std::cout << "Outer loop\n";
        for (int j = 0; j < 5; j++) {
            std::cout << "Inner loop\n";
        }
        std::cout << "\n";
    }
    return 0;
}

If the code ran successfully, it should display the below text, repeated 10 times:

Outer loop
Inner loop
Inner loop
Inner loop
Inner loop
Inner loop

Note that loops’ variables often start at the letter “i”, with each nested loop using the next letter in the alphabet.

Break and Continue

If you ever need to exit out of a loop before the loop is finished, you can use break;. See how it works in the code below:

#include <iostream>

int main() {
    for (int i = 0; i < 10; i++) {
        if (i == 6) {
            break;
        }
        std::cout << i << "\n";
    }
    std::cout << "For loop ended!\n";
    return 0;
}

The use of break; above causes only the numbers 0 to 5 to be printed to the screen (since the loop is exited when i equals 6).

If you ever need to “skip” a value in a loop, you can use continue; :

#include <iostream>

int main() {
    for (int i = 0; i < 10; i++) {
        if (i == 6) {
            continue;
        }
        std::cout << i << "\n";
    }
    std::cout << "For loop ended!\n";
    return 0;
}

Here, all the numbers from 0 to 9 are printed to the screen except 6, which is “skipped” by using continue;.

Challenge Problem

Write a program that loops through every number from 2 to 100 and, for each number, prints that number to the screen if it is a prime. (A prime number is any number that isn’t divisible by anything except the number 1 and itself.)

A few hints:

  • For each number, you’ll also need a nested loop to check if the number is divisible by any number smaller than it.
    • If you’d like your program to run as fast as it can, you actually don’t need to check divisibility by every number that’s smaller than the current number (just every number that’s less than or equal to the square root of the current number). You can take the square root of a number by adding #include <cmath> to the top of your program and using sqrt(numberToSquareRoot).
  • After finding a number that the outer loop’s number is divisible by, there’s no need to keep checking divisibility by more numbers (since you then know the outer loop’s number is not a prime). Therefore, you can just “break” out of the inner loop.
  • You can use the modulo operator (%) to check if a number is divisible by another number. Try to think of how this can work.

If you get stuck, check out my solution here.