Skip to content

Loops: for, while, do-while

Programming C++ Difficulty 1/5

Beginning of the lesson

Loops: for, while, do-while

Teach the computer to repeat work for you

Big Idea: A loop lets you run the same block of code many times without copying it over and over. Instead of writing cout five times, you write it once inside a loop and tell the loop how many times to repeat.
By the end you will be able to:
  • write a for, a while, and a do-while loop,
  • choose the right loop for the job,
  • control a loop with break and continue.

1. What is a loop?

Imagine you are told: "Do ten push-ups." You do not get ten separate instructions. You get one instruction plus a rule: repeat until you reach ten. That is exactly what a loop is - one block of code plus a rule that says how long to keep repeating.

Every loop needs three things to be safe: a start (where do we begin?), a condition (should we keep going?), and a change (something that moves us toward stopping). If the change is missing, the condition never becomes false and the loop runs forever - an infinite loop.

2. The for loop - when you know the count

A for loop packs all three parts onto one line: for (start; condition; change). Use it when you know how many times to repeat.

#include <iostream>
using namespace std;

int main() {
    for (int i = 1; i <= 5; i++) {
        cout << i << " ";
    }
    cout << endl;
    return 0;
}

Output:

1 2 3 4 5

Read the header for (int i = 1; i <= 5; i++) as three steps:

  • int i = 1 - the start: create a counter and set it to 1 (runs once).
  • i <= 5 - the condition: keep looping while this is true.
  • i++ - the change: add 1 to i after each pass.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers