TeqStudy ยท C++ Track ยท Phase 02

C++ Loops

while, do-while, for, nested loops, break/continue, and the recurring patterns you'll reuse in nearly every program you write. Ends with a real number-guessing game.

๐Ÿ” ๐Ÿ”‚ ๐Ÿ”ข ๐Ÿช† ๐Ÿ
Course Progress
0%
MODULE 01

๐Ÿ” while Loops

The Pre-Course described "repeat until a condition changes" โ€” stirring sauce until it thickens. This is that exact idea, in real C++.

๐Ÿ”‚ The Shape of a while Loop
C++
int count = 0;
while (count < 5) {
    std::cout << count << std::endl;
    count++;
}

Read it as: "while this condition is true, keep running the block." Before every single repetition, C++ checks the condition first โ€” if it's already false the very first time, the loop body never runs at all, not even once.

โž•โž– Increment and Decrement Shortcuts
ShortcutEquivalent To
count++count = count + 1
count--count = count - 1
count += 5count = count + 5
count -= 5count = count - 5

You'll see count++ constantly in loops โ€” it's simply the conventional, compact way to write "add one to this variable."

โš ๏ธ The #1 Mistake โ€” Forgetting to Update the Condition
C++ โ€” infinite loop!
int count = 0;
while (count < 5) {
    std::cout << count << std::endl;
    // forgot count++ โ€” this loop NEVER ends
}
โš ๏ธ
This is the "infinite loop" the Pre-Course warned aboutWithout something inside the loop that eventually makes the condition false, while runs forever, freezing your program. If a program you run seems to hang, check every loop's condition for exactly this โ€” a genuinely common early mistake, easy to fix once you know what to look for.
๐Ÿง  Quick Check
If a while loop's condition is false the very first time it's checked, how many times does the loop body run?
MODULE 02

๐Ÿ”‚ do-while Loops

A small but genuinely useful variation on while โ€” for situations where you need the loop body to run at least once, no matter what.

๐Ÿ”„ Checking AFTER Instead of Before
C++
int choice;
do {
    std::cout << "Enter 1-5: ";
    std::cin >> choice;
} while (choice < 1 || choice > 5);

A do-while loop runs its body FIRST, then checks the condition โ€” meaning the body always runs at least once, even if the condition would've been false from the start. This fits menu-style prompts perfectly: you have to ask the user for input at least once before you have anything to validate.

๐Ÿ†š while vs. do-while โ€” Choosing the Right One
SituationBetter Fit
You might not need to run the body at allwhile
You need the body to run at least once, always (like getting initial input to validate)do-while
๐Ÿง  Quick Check
Why is do-while a natural fit for a menu prompt that validates user input?
MODULE 03

๐Ÿ”ข for Loops

The Pre-Course's "20 push-ups" example โ€” repeating a known number of times โ€” has its own dedicated, compact syntax in C++.

๐Ÿ” Breaking Down the Three Parts
C++
for (int i = 0; i < 20; i++) {
    std::cout << "Push-up #" << (i + 1) << std::endl;
}
PartMeaningRuns
int i = 0Starting pointOnce, before the loop begins
i < 20Condition โ€” keep going while trueBefore every repetition
i++UpdateAfter every repetition

This is exactly equivalent to a while loop with the counter setup, condition, and increment all written manually โ€” for just bundles all three into one compact, less error-prone line, specifically because forgetting the increment (Module 1's classic bug) is much harder when it's built right into the loop's own header.

๐Ÿ” for vs. while โ€” When to Use Which
SituationBetter Fit
You know exactly how many repetitions you needfor
You're repeating until some condition changes, with an unknown repeat countwhile

Both are fully capable of doing either job โ€” this is a readability convention, not a hard technical rule.

๐Ÿง  Quick Check
In for (int i = 0; i < 20; i++), in what order do the three parts actually execute?
MODULE 04

๐Ÿช† Nested Loops

A loop can contain another loop inside it. This is how you handle anything grid-shaped โ€” rows and columns, a game board, a multiplication table.

๐Ÿ”ฒ A Loop Inside a Loop
C++
for (int row = 1; row <= 3; row++) {
    for (int col = 1; col <= 3; col++) {
        std::cout << row * col << " ";
    }
    std::cout << std::endl;
}

For every single repetition of the OUTER loop (each row), the ENTIRE inner loop runs completely (all three columns) before the outer loop moves to its next repetition. This produces a 3ร—3 multiplication grid, one row printed per outer-loop repetition.

๐Ÿงฎ Counting the Total Repetitions

If the outer loop runs 3 times and the inner loop runs 3 times for EACH of those, the inner loop's body actually executes 3 ร— 3 = 9 times total. This multiplies quickly โ€” a 100ร—100 nested loop runs its innermost code 10,000 times โ€” which matters once you start thinking about how long a program takes to run on larger amounts of data.

๐Ÿ’ก
Use different variable names for each loop levelrow and col are far clearer than reusing i for both โ€” and reusing the exact same variable name for both loops is a genuine C++ error (or at minimum, deeply confusing code) since the inner loop's variable would shadow or conflict with the outer one.
๐Ÿง  Quick Check
An outer loop runs 4 times, and its inner loop runs 5 times for each outer repetition. How many total times does the inner loop's body execute?
MODULE 05

โญ๏ธ break & continue

Two keywords for interrupting a loop's normal flow โ€” one exits it entirely, the other just skips ahead to the next repetition.

๐Ÿ›‘ break โ€” Exit the Loop Immediately
C++
for (int i = 1; i <= 100; i++) {
    if (i == 10) {
        break;   // exits the loop entirely, right here
    }
    std::cout << i << " ";
}
// prints 1 2 3 4 5 6 7 8 9, then stops โ€” the loop never reaches 100

break immediately stops the loop, regardless of its normal condition โ€” useful for something like searching a list and stopping the moment you find what you're looking for, instead of wastefully continuing to check everything else.

โฉ continue โ€” Skip to the Next Repetition
C++
for (int i = 1; i <= 10; i++) {
    if (i % 2 == 0) {
        continue;   // skip printing even numbers
    }
    std::cout << i << " ";
}
// prints 1 3 5 7 9 โ€” evens are skipped, but the loop keeps going

Unlike break, continue doesn't exit the loop โ€” it just skips the REST of the current repetition's body and jumps straight to the next one (running the update step, then re-checking the condition, as normal).

๐Ÿง  Quick Check
What's the key difference between what break and continue actually do?
MODULE 06

๐Ÿงฉ Common Loop Patterns

Three shapes of loop-based logic you'll reuse constantly, across essentially every program you ever write.

โž• The Accumulator Pattern

Building up a running total across repetitions:

C++
int total = 0;
for (int i = 1; i <= 10; i++) {
    total += i;   // total = total + i
}
// total is now 55 (1+2+3+...+10)

The variable being accumulated into (total) must be declared and initialized BEFORE the loop starts โ€” a genuinely common mistake is declaring it inside the loop, which resets it to 0 every single repetition instead of accumulating.

๐Ÿ” The Search Pattern

Looking for a specific item and stopping once found, using break from the last lesson:

C++
bool found = false;
for (int i = 1; i <= 100; i++) {
    if (i == targetValue) {
        found = true;
        break;
    }
}
๐Ÿšช The Sentinel Pattern

Repeating until the user enters a special "stop" value:

C++
int number;
std::cout << "Enter numbers, or -1 to stop: ";
std::cin >> number;
while (number != -1) {
    std::cout << "You entered: " << number << std::endl;
    std::cin >> number;
}

Notice the input is read TWICE โ€” once before the loop starts (to have something to check the very first time) and once at the end of every repetition (to get the next value). This shape is worth recognizing on sight.

๐Ÿง  Quick Check
In the accumulator pattern, why must the total variable be initialized OUTSIDE (before) the loop, not inside it?
MODULE 07

๐Ÿ•ณ๏ธ Loop Pitfalls

The specific, recurring mistakes almost everyone makes with loops at some point โ€” worth knowing about in advance rather than discovering the hard way.

1๏ธโƒฃ Off-by-One Errors
C++ โ€” which is right?
for (int i = 0; i < 10; i++)   // runs 10 times: 0,1,2...9
for (int i = 0; i <= 10; i++)  // runs 11 times: 0,1,2...10

The difference between < and <= shifts the total number of repetitions by exactly one โ€” this class of mistake is common enough to have its own name ("off-by-one") and is genuinely easy to introduce even once you're experienced. When a loop's count seems wrong by exactly one, this is the very first thing to check.

2๏ธโƒฃ Modifying the Loop Variable Inside the Body

Changing the loop's counter variable somewhere inside the body โ€” separately from the loop's own update step โ€” makes the loop's behavior confusing and hard to predict. It's technically legal C++, but almost always a sign of a design that should be restructured.

3๏ธโƒฃ Infinite Loops (Revisited)

Module 1 already covered the classic version (forgetting to update the condition variable). A second common version: a condition that can genuinely never become false due to a logic mistake โ€” like accidentally using || (OR) where you meant && (AND), making the condition true far more often than intended.

๐Ÿ’ก
If a loop hangs, print the counterA quick, genuinely effective debugging trick: add a temporary std::cout << i << std::endl; inside a suspicious loop and watch what actually happens. Seeing the real values (does it count up forever? does it jump unexpectedly?) usually reveals the bug immediately.
๐Ÿง  Quick Check
A loop meant to run exactly 10 times instead runs 11 times. What's the most likely cause?
MODULE 08 ๐Ÿ

๐Ÿ Capstone โ€” Number Guessing Game

Every idea from this phase, combined: a loop that repeats until a condition is met, using the sentinel and accumulator patterns, break, and everything from Phase 1.

๐ŸŽฏ The Goal

The computer picks a secret number between 1 and 100. The player guesses repeatedly; after each guess, the program says "too high," "too low," or "correct!" โ€” and tracks how many guesses it took.

๐Ÿ’ป A Reference Solution
main.cpp
#include <iostream>

int main() {
    int secret = 42;  // hardcoded for now โ€” random numbers come in a later phase
    int guess = 0;
    int attempts = 0;

    std::cout << "I'm thinking of a number between 1 and 100." << std::endl;

    while (guess != secret) {
        std::cout << "Your guess: ";
        std::cin >> guess;
        attempts++;

        if (guess < secret) {
            std::cout << "Too low!" << std::endl;
        } else if (guess > secret) {
            std::cout << "Too high!" << std::endl;
        } else {
            std::cout << "Correct! You got it in " << attempts << " attempts." << std::endl;
        }
    }

    return 0;
}
๐Ÿ” Why It's Built This Way
  • The while (guess != secret) condition is a direct application of Module 1 โ€” keep going until the exact right condition is met.
  • attempts is the accumulator pattern from Module 6, counting up by one each repetition.
  • The if/else-if/else chain inside the loop is Phase 1's Module 8, reused here to give feedback each guess.
๐Ÿ Extend It Yourself

Add a Guess Limit

Modify the game so the player only gets 7 guesses โ€” using break from Module 5 to exit the loop early if they run out, with a "you lose" message. This requires combining a loop condition (guess != secret) with an INSIDE-the-loop check (have they used all 7 attempts?) โ€” genuinely representative of the kind of layered logic real programs need.

Roadmap