SyntaxPilot
Courses/C++/Lesson 6

C++ · Lesson 6 of 40 · 16 min

Loops

queued

These are the notes for C++ episode 6. Last episode your program learned to make decisions with if, else and switch. Here it learns to repeat. You will see why copy-pasting the same line fails, invent the while loop (condition, body, update), meet the infinite loop, move start, check and step onto one line with for, catch off-by-one errors, add up a bill of unknown length with cin and a sentinel, build a menu with do-while, stop early with break, skip a round with continue, and print a pattern with a loop inside a loop. Every example below was compiled with g++ -O2 -std=c++17 main.cpp -o main (g++ 13.3, the same command as the SyntaxPilot compiler) and run with the input shown, using printf '<input>' | ./main.

Short snippets. When only the inside of main is shown, put those lines into this skeleton. That is exactly what the video runs.

```cpp

include

include

using namespace std;

int main() { // the lines go here return 0; } ```

The problem: 100 meal coupons, copy-pasted

Aman's hostel mess feeds 100 students, and the manager wants numbered meal coupons: Coupon 1 to Coupon 100. Aman's obvious attempt: one cout per coupon, copy, paste, change the number.

cout << "Coupon 1" << endl;
cout << "Coupon 2" << endl;
cout << "Coupon 3" << endl;
cout << "Coupon 3" << endl;
cout << "Coupon 5" << endl;

Output:

Coupon 1
Coupon 2
Coupon 3
Coupon 3
Coupon 5

Coupon 3 is printed twice and coupon 4 is missing: he pasted the line and forgot to change the number. And that's only five lines. For 100 coupons it's 100 lines and 100 chances for a typo; for 500 tomorrow, 400 more pastes.

Why it failed: the line is the same every time. Only the number changes, and it grows by 1. What we really want to say is "write this line once, and repeat it while the number is at most 100." A loop is exactly that: a piece of code that runs again and again as long as a condition is true.

The fix: the while loop

Think of watering a row of plants:

In the garden In C++ Name
Start at plant 1 int coupon = 1; the counter starts (a counter is a variable that counts)
Any plant left? Check first while (coupon <= 5) the condition, checked before every round
Water it cout << "Coupon " << coupon << endl; the body: the lines inside { } that repeat
Move to the next plant coupon++; the update: moves the loop towards its end
int coupon = 1;
while (coupon <= 5) {
    cout << "Coupon " << coupon << endl;
    coupon++;
}

Output:

Coupon 1
Coupon 2
Coupon 3
Coupon 4
Coupon 5

No typo is possible: the number comes from the counter, not from your fingers. For 100 coupons change one number, 5 → 100; the output ends with Coupon 98, Coupon 99, Coupon 100.

How it runs: check coupon <= 5 → true → run the body (print, coupon++) → check again ... When coupon becomes 6, the check is false and the program continues after the closing }. Each trip round the loop is one iteration; this loop does 5 iterations (100 with <= 100).

coupon++ is the increment operator from episode 3: it adds 1 (same as coupon = coupon + 1).

The loop that never ends: infinite loops

What if the update line is forgotten?

int coupon = 1;
while (coupon <= 100) {
    cout << "Coupon " << coupon << endl;
}

coupon stays 1 forever. Is 1 ≤ 100? Yes, print. Is 1 ≤ 100? Yes, print. It prints Coupon 1, Coupon 1, Coupon 1 ... and never stops. This is an infinite loop: a loop whose condition never becomes false. g++ compiles it without a word, because it is not a syntax error but a logic error (a mistake in what the code means). On your computer stop it with Ctrl + C; an online compiler stops it after its time limit.

Rule: every loop needs something inside it that moves it towards the end.

for: start, check and step on one line

In the while loop, the three parts live in three places: the start above the loop, the check in the while, and the step hidden at the bottom of the body (the line people forget). Counting loops are so common that C++ gives them their own keyword:

for (start; check; step) {
    body
}

Real-life example, one over in cricket:

In cricket In C++ When it runs
First ball: ball 1 int ball = 1 once, at the start
Six balls done yet? ball <= 6 before every round
Umpire counts the next ball ball++ after every round
for (int coupon = 1; coupon <= 5; coupon++) {
    cout << "Coupon " << coupon << endl;
}

Output: Coupon 1 to Coupon 5, exactly like the while loop, in three lines instead of five. The three parts are separated by semicolons.

The 7 times table:

for (int i = 1; i <= 10; i++) {
    cout << "7 x " << i << " = " << 7 * i << endl;
}

Output:

7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70

i is the traditional name for a loop counter (short for index). A variable declared in the for brackets exists only inside the loop: using i after the loop's } is an error ('i' was not declared in this scope).

while or for? Use for when you know how many rounds (count from 1 to 10). Use while when you don't (keep reading until the user types 0).

Off-by-one errors

The umpire writes ball < 6 instead of ball <= 6: balls 1, 2, 3, 4, 5, then "is 6 < 6?" is false, and the over ends with five balls. The same in code:

for (int i = 1; i < 10; i++) {
    cout << "7 x " << i << " = " << 7 * i << endl;
}

Output stops at 7 x 9 = 63; the line 7 x 10 = 70 is missing. No error, no warning. A loop that runs one time too few or one time too many has an off-by-one error, the most common loop bug of all.

Quick test: always check the first and the last round.

Loop header Values of i Rounds
for (int i = 1; i <= 10; i++) 1 ... 10 10
for (int i = 1; i < 10; i++) 1 ... 9 9 (off by one if you wanted 10)
for (int i = 0; i < 10; i++) 0 ... 9 10
for (int i = 0; i <= 10; i++) 0 ... 10 11

Adding up a bill with cin: sentinel and running total

At the kirana shop, the shopkeeper types the price of each item, but nobody knows in advance how many items there are. So when the customer says "bas", he types 0. A special value that means "stop", like this 0, is called a sentinel. While prices come in, he keeps adding them: a running total.

At the shop In C++
The cash box starts empty int total = 0;
Each payment goes in total += price; (short for total = total + price;)
Counted at closing cout << total; after the loop
int price, total = 0;
cin >> price;
while (price != 0) {
    total += price;
    cin >> price;
}
cout << "Total: " << total << endl;

Input 40 25 60 0 → output Total: 125.

  • cin appears twice: once before the loop, so the first check has a price to look at, and once at the end of the body to read the next price. That second cin is this loop's update.
  • The total must start at 0. Without = 0 it holds a garbage value (whatever was in memory).
  • The sentinel is not added: the check price != 0 stops the loop before total += price sees it.

do-while: run at least once

The mess wants a menu screen: show 1 Breakfast 2 Lunch 3 Exit, read the choice, and come back until the student picks 3. A while loop checks before the first round, but nobody has chosen anything yet. The menu must show at least once, before there's anything to check. do-while runs the body first and checks afterwards:

int choice;
do {
    cout << "1 Breakfast  2 Lunch  3 Exit" << endl;
    cin >> choice;
    cout << "You chose " << choice << endl;
} while (choice != 3);
cout << "Thank you!" << endl;

Input 1 2 3:

1 Breakfast  2 Lunch  3 Exit
You chose 1
1 Breakfast  2 Lunch  3 Exit
You chose 2
1 Breakfast  2 Lunch  3 Exit
You chose 3
Thank you!

Input 3:

1 Breakfast  2 Lunch  3 Exit
You chose 3
Thank you!

The body always runs at least once. do-while is the only loop that ends with a semicolon after while (...).

Loop Checks Minimum rounds Typical use
while before each round 0 unknown count (read until 0)
for before each round 0 known count (1 to 10)
do-while after each round 1 menus, "ask again?"

break and continue

In real life In C++ Effect
A bunch of 10 keys: key 4 opens the lock, so you stop trying break; leaves the loop immediately
The bus skips stops where nobody waits, but the route goes on continue; skips the rest of this round, jumps to the next one
for (int key = 1; key <= 10; key++) {
    cout << "Trying key " << key << endl;
    if (key == 4) {
        cout << "Lock opened!" << endl;
        break;
    }
}

Output:

Trying key 1
Trying key 2
Trying key 3
Trying key 4
Lock opened!

The loop was ready to go to 10, but break ended it at 4.

for (int stop = 1; stop <= 8; stop++) {
    if (stop % 3 == 0) {
        continue;
    }
    cout << "Bus stops at " << stop << endl;
}

Output:

Bus stops at 1
Bus stops at 2
Bus stops at 4
Bus stops at 5
Bus stops at 7
Bus stops at 8

% (modulo) gives the remainder, so stop % 3 == 0 means "the stop number divides by 3". continue skipped only the cout for stops 3 and 6; in a for loop the step (stop++) still runs, and the loop carried on to 8.

In a while loop, continue jumps straight to the check. If the update is below the continue, it is skipped too, and you can get an infinite loop. Put the update before the continue, or use for.

Nested loops: a loop inside a loop

A Diwali laddoo pyramid: row 1 has 1 laddoo, row 2 has 2, row 3 has 3, row 4 has 4. For every row, place the laddoos one by one: a repeat inside a repeat. A loop inside another loop is a nested loop. The outer loop goes over the rows; the inner loop places the laddoos in one row.

for (int row = 1; row <= 4; row++) {
    for (int col = 1; col <= row; col++) {
        cout << "* ";
    }
    cout << endl;
}

Output:

* 
* * 
* * * 
* * * * 

For row = 1 the inner loop runs once, for row = 2 twice, and so on. The inner loop finishes all its rounds before the outer loop takes one step, like a clock whose minute hand goes all the way round for every step of the hour hand. cout << endl is outside the inner loop, so each row ends with a new line. Total work multiplies: an outer loop of 3 and an inner loop of 4 run the body 3 × 4 = 12 times.

Common mistakes (and the real g++ messages)

Mistake Code What g++ says / what happens Fix
Commas instead of semicolons in for for (int i = 1, i <= 3, i++) error: expected ';' before '<=' token (then expected primary-expression before '<=' token and expected ';' before ')' token) for (int i = 1; i <= 3; i++)
Semicolon after the for brackets for (int i = 1; i <= 3; i++); then { cout << "Hello" << endl; } no error; Hello prints once (the ; is an empty body) remove the ; before {
Using the for variable inside a block after a stray ; for (...); then { cout << i; } error: 'i' was not declared in this scope remove the ;
Forgetting the update while (coupon <= 100) { cout << ...; } no error; prints Coupon 1 forever (infinite loop) add coupon++; inside
Off by one for (int i = 1; i < 10; i++) no error; 7 x 10 missing i <= 10 (check the first and last round)
Missing ; after do-while } while (choice != 3) error: expected ';' before 'cout' (pointing at the next line) } while (choice != 3);
Total not set to 0 int total; then total += price; no error; garbage total int total = 0;

The stray semicolon with Hello (fixed version prints Hello three times):

for (int i = 1; i <= 3; i++);
{
    cout << "Hello" << endl;
}

Output: Hello (once). The loop repeated an empty statement three times, then the block ran once on its own.

Mini project: phone PIN with 3 tries

A lock screen asks for a PIN. A wrong PIN uses a try and says how many are left; the right PIN unlocks and stops asking (break); after three wrong tries the phone locks.

#include <iostream>
using namespace std;
int main() {
    int pin, tries = 0;
    bool ok = false;
    while (tries < 3) {
        cout << "Enter PIN: ";
        cin >> pin;
        tries++;
        if (pin == 4321) {
            ok = true;
            break;
        }
        cout << "Wrong PIN. " << 3 - tries << " left" << endl;
    }
    if (ok) cout << "Welcome! Balance: 5000" << endl;
    else cout << "Phone locked!" << endl;
    return 0;
}

Input 1111 then 4321:

Enter PIN: Wrong PIN. 2 left
Enter PIN: Welcome! Balance: 5000

Input 1, 2, 3:

Enter PIN: Wrong PIN. 2 left
Enter PIN: Wrong PIN. 1 left
Enter PIN: Wrong PIN. 0 left
Phone locked!

(Piped input is not echoed, so the PIN you typed doesn't appear after Enter PIN:.)

  • tries is the counter; tries < 3 allows exactly three rounds (0, 1, 2 before the increment).
  • ok is a flag: a bool that remembers something. After the loop it tells us why the loop ended: break (right PIN) or the condition became false (three wrong tries).
  • Extend it: lock for 30 seconds instead, or allow the user to change the PIN.

Practice

  1. Read a number and print its times table from 1 to 10.
  2. Read numbers until 0 and print the largest.
  3. Print the sum of the digits of 4721 (the answer is 14).
  4. Print a 5-row pyramid of numbers: 1, 1 2, 1 2 3 ...
Solution

1. Input 12 ends with 12 x 9 = 108, 12 x 10 = 120.

int n;
cin >> n;
for (int i = 1; i <= 10; i++) {
    cout << n << " x " << i << " = " << n * i << endl;
}

2. Start largest at the first number (not at 0, so negative numbers also work). Input 45 12 99 7 0 prints Largest: 99.

int x, largest;
cin >> x;
largest = x;
while (x != 0) {
    if (x > largest) {
        largest = x;
    }
    cin >> x;
}
cout << "Largest: " << largest << endl;

3. n % 10 is the last digit, n /= 10 removes it (integer division). Prints Sum of digits: 14 (1 + 2 + 7 + 4).

int n = 4721, sum = 0;
while (n > 0) {
    sum += n % 10;
    n /= 10;
}
cout << "Sum of digits: " << sum << endl;

4. Print col instead of a star.

for (int row = 1; row <= 5; row++) {
    for (int col = 1; col <= row; col++) {
        cout << col << " ";
    }
    cout << endl;
}

Output:

1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5 

Quick quiz

How many times is Hi printed?

for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 4; j++) {
        cout << "Hi ";
    }
}
  • A. 7
  • B. 12
  • C. 3
  • D. 4
Answer

B: 12. The outer loop runs 3 times (i = 0, 1, 2); each time, the inner loop runs 4 times (j = 0 to 3). 3 × 4 = 12. Verified output: Hi Hi Hi Hi Hi Hi Hi Hi Hi Hi Hi Hi.

Interview questions

  • What is the difference between while and do-while? while checks the condition before each round, so its body may run zero times; do-while checks after each round, so its body runs at least once.
  • When would you use for instead of while? When the number of rounds is known or you are counting (for (int i = 0; i < n; i++)); while is for an unknown count, e.g. reading until a sentinel.
  • What is an infinite loop? Can it be useful? A loop whose condition never becomes false. It is usually a bug (missing update), but deliberate ones like while (true) with a break inside are used for servers, games and menus.
  • What is the difference between break and continue? break exits the innermost loop immediately; continue skips the rest of the current round and goes to the next check (in a for, after running the step).
  • Does break in an inner loop stop the outer loop? No, only the innermost loop (or switch) it is in.
  • What is an off-by-one error and how do you avoid it? A loop that runs one time too many or too few, usually < vs <= or starting at 0 vs 1. Check the first and last values by hand.
  • What does for (int i = 0; i < 3; i++); do? The ; is an empty body: the loop runs three times doing nothing, and the block after it runs once.
  • What is the scope of a variable declared in a for header? Only the loop itself; it does not exist after the closing }.
  • How many times does the body of nested loops of sizes n and m run? n × m.

Glossary

Term Plain meaning Example
Loop Code that runs again and again as long as a condition is true while (coupon <= 100) { ... }
Iteration One trip round a loop the loop above does 100 iterations
Condition A true/false question checked to decide whether to go round again coupon <= 5
Body The lines inside the loop's { } that are repeated cout << coupon;
Counter A variable that counts the rounds int coupon = 1;
Update The step that moves the loop towards its end coupon++;
++ (increment) Adds 1 to a variable i++ is i = i + 1
while Repeats its body while the condition is true; checks first while (price != 0)
for A counting loop with start, check and step on one line for (int i = 1; i <= 10; i++)
do-while Runs the body first, then checks; at least one round; ends with ; do { ... } while (choice != 3);
Infinite loop A loop whose condition never becomes false forgetting coupon++
Logic error The code compiles but does the wrong thing an infinite loop, off-by-one
Syntax error Code that breaks C++'s grammar; g++ refuses to compile it for (int i = 1, i <= 3, i++)
Off-by-one error A loop that runs one time too many or too few i < 10 instead of i <= 10
Index A position number; i is short for it i in for (int i = 0; ...)
Sentinel A special input value that means "stop" typing 0 at the end of the bill
Running total A total that grows as each value is added total += price;
+= Adds to a variable: a += b is a = a + b total += 40;
/= Divides a variable: a /= b is a = a / b n /= 10;
% (modulo) The remainder after division 7 % 3 is 1; 6 % 3 is 0
Garbage value Whatever happens to be in memory in a variable that was never set int total; before = 0
break Leaves the loop immediately stop at the key that opens the lock
continue Skips the rest of this round and goes to the next skip stops 3 and 6
Nested loop A loop inside another loop rows × stars
Outer / inner loop In a nested loop: the one outside (rows) and the one inside (items in a row) row / col
Scope The part of the code where a variable exists a for variable exists only in the loop
Flag A bool that remembers whether something happened bool ok = false;
bool A type with only two values, true and false ok = true;
Ctrl + C The key combination that stops a running program in a terminal stopping an infinite loop

Summary

  • Copy-pasting the same line breeds typos; a loop writes it once and repeats it.
  • while (condition) { body }: check, work, update. Every loop needs an update that moves it towards the end, or it is an infinite loop.
  • for (start; check; step) puts the three parts on one line: use it for counting.
  • Off-by-one: check the first and the last round (< vs <=, starting at 0 vs 1).
  • Unknown count: read until a sentinel (like 0), building a running total with +=, starting at 0.
  • do { } while (condition); runs at least once: perfect for menus. Don't forget the final ;.
  • break leaves the loop; continue skips the rest of the round.
  • Nested loops: the inner loop finishes first; the work multiplies (3 × 4 = 12).

Next episode: functions and overloading. Loops stop you repeating the same line, but what about the same block of code in five different places, like the GST calculation on every bill? Next time you'll invent functions, and give one name to many jobs with overloading.