Skip to main content

📝 Lesson 5: Loops

Master the art of automating repetitive tasks using C++ loops.

🎯 Learning Objectives

By the end of this lesson, you will be able to:

  • Understand the necessity of loops for automating repetitive tasks.
  • Implement and differentiate between FOR, WHILE, and DO-WHILE loops.
  • Utilize nested loops to handle multidimensional data and patterns.
  • Control loop execution flow using break and continue statements.

Estimated Time: 60–90 minutes

Project: Build a number guessing game using a DO-WHILE loop for input validation and game flow.

In This Lesson

Why Do We Need Loops?

Imagine having to write "I will not throw paper airplanes" 100 times on the blackboard. Would you rather write the same line 100 times, or tell someone "Write this line 100 times"? That's exactly what loops do - they automate repetition!

The Three Types of Loops

graph TD A[C++ Loops] --> B[FOR Loop] A --> C[WHILE Loop] A --> D[DO-WHILE Loop] B --> E["When you know<br/>how many times"] C --> F["When you have<br/>a condition"] D --> G["When you need<br/>at least once"] E --> H[Count to 10] F --> I[Until user says stop] G --> J[Menu systems]

The FOR Loop: The Counting Loop

The FOR loop is like a precise counter - perfect when you know exactly how many times to repeat.

Anatomy of a FOR Loop for (int i = 0; i < 5; i++) Initialization Start value Condition Keep going? Update Change counter Flow: Init → Check → Run → Update → Check...

FOR Loop Examples

// Count from 1 to 10
for (int i = 1; i <= 10; i++) {
    cout << i << " ";
}
// Output: 1 2 3 4 5 6 7 8 9 10

// Count backwards
for (int i = 10; i >= 1; i--) {
    cout << i << " ";
}
// Output: 10 9 8 7 6 5 4 3 2 1

// Count by 2s
for (int i = 0; i <= 20; i += 2) {
    cout << i << " ";
}
// Output: 0 2 4 6 8 10 12 14 16 18 20

💡 Modern C++: Use a counting for loop when you truly need the index. But when you just want to visit every element of a container (an array, vector, or Unreal's TArray), prefer a range-based for loop: for (const auto& item : items) { ... }. It is clearer and sidesteps off-by-one and out-of-bounds bugs. C++20 also adds std::ranges and views (such as std::views::filter) for composing loops declaratively. We'll lean on range-based loops throughout the Arrays & Strings lesson.

Loop Visualization: See It In Action

The WHILE Loop: The Conditional Loop

WHILE loops are like a security guard asking "Do you have permission?" - they keep going as long as the answer is yes!

graph TD A[Start] --> B{Condition True?} B -->|Yes| C[Execute Loop Body] C --> D[Update Variables] D --> B B -->|No| E[Exit Loop] E --> F[Continue Program]

WHILE Loop Examples

// Basic while loop
int count = 0;
while (count < 5) {
    cout << "Count is: " << count << '\n';
    count++;
}

// User-controlled loop
char answer = 'y';
while (answer == 'y' || answer == 'Y') {
    cout << "Continue? (y/n): ";
    cin >> answer;
}

// Input validation
int age;
cout << "Enter your age (1-120): ";
cin >> age;
while (age < 1 || age > 120) {
    cout << "Invalid age! Try again: ";
    cin >> age;
}

The DO-WHILE Loop: The "At Least Once" Loop

DO-WHILE is like trying food before deciding if you like it - you do it first, then decide whether to continue.

DO-WHILE Example: Menu System

int choice;
do {
    cout << "\n=== MENU ===" << '\n';
    cout << "1. Play Game" << '\n';
    cout << "2. View Scores" << '\n';
    cout << "3. Settings" << '\n';
    cout << "4. Exit" << '\n';
    cout << "Choose (1-4): ";
    cin >> choice;

    switch(choice) {
        case 1:
            cout << "Starting game..." << '\n';
            break;
        case 2:
            cout << "High scores..." << '\n';
            break;
        case 3:
            cout << "Settings..." << '\n';
            break;
        case 4:
            cout << "Goodbye!" << '\n';
            break;
        default:
            cout << "Invalid choice!" << '\n';
    }
} while (choice != 4);

Nested Loops: Loops Within Loops

Nested loops are like a clock - the minute hand completes a full rotation for each hour!

Nested Loop Visualization Outer Loop (i = 0 to 2) i = 0 j = 0 j = 1 j = 2 i = 1 j = 0 j = 1 j = 2 i = 2 j = 0 j = 1 j = 2

Nested Loop Examples

// Print a rectangle of stars
for (int i = 0; i < 4; i++) {      // Rows
    for (int j = 0; j < 6; j++) {  // Columns
        cout << "* ";
    }
    cout << '\n';
}
/* Output:
* * * * * *
* * * * * *
* * * * * *
* * * * * *
*/

// Multiplication table
for (int i = 1; i <= 5; i++) {
    for (int j = 1; j <= 5; j++) {
        cout << i * j << "\t";
    }
    cout << '\n';
}
/* Output:
1    2    3    4    5
2    4    6    8    10
3    6    9    12   15
4    8    12   16   20
5    10   15   20   25
*/

Loop Control: Break and Continue

BREAK and CONTINUE are like emergency controls - BREAK is the emergency exit, CONTINUE is the skip button!

Break and Continue Examples

// Break example - find first number divisible by 7
for (int i = 1; i <= 100; i++) {
    if (i % 7 == 0) {
        cout << "First number divisible by 7: " << i << '\n';
        break;  // Exit loop
    }
}

// Continue example - print only odd numbers
for (int i = 1; i <= 10; i++) {
    if (i % 2 == 0) {
        continue;  // Skip even numbers
    }
    cout << i << " ";
}
// Output: 1 3 5 7 9

Infinite Loops: Handle with Care!

Infinite loops are like a hamster wheel - they keep going forever unless you stop them!

graph TD A[Infinite Loop Warning] --> B[while true] A --> C[for ;;] A --> D[Forgot to update] B --> E["while(true) {<br/> // Need break!<br/>}"] C --> F["for(;;) {<br/> // Need break!<br/>}"] D --> G["while(x < 10) {<br/> // Forgot x++<br/>}"] E --> H[Use break to exit] F --> H G --> I[Always update variables]

Practice Exercise: Number Guessing Game

🏋️ Build a Guessing Game!

Create a number guessing game that:

  1. Generates a random number between 1 and 100
  2. Asks the user to guess
  3. Tells them if they're too high or too low
  4. Counts the number of guesses
  5. Congratulates them when they guess correctly
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main() {
    srand(time(nullptr));  // Seed random number generator
    int secretNumber = rand() % 100 + 1;  // 1-100
    int guess;
    int attempts = 0;

    cout << "I'm thinking of a number between 1 and 100!" << '\n';

    // TODO: Use a do-while loop for the game
    // Hint: Keep looping while guess != secretNumber

    return 0;
}
✅ Solution
do {
    cout << "Enter your guess: ";
    cin >> guess;
    attempts++;

    if (guess > secretNumber) {
        cout << "Too high! Try again." << '\n';
    } else if (guess < secretNumber) {
        cout << "Too low! Try again." << '\n';
    } else {
        cout << "Congratulations! You got it!" << '\n';
        cout << "It took you " << attempts << " guesses." << '\n';
    }
} while (guess != secretNumber);

Loop Patterns: Common Use Cases

Common Loop Patterns Counter Pattern for(int i=0; i<n; i++) { // Process item i } Accumulator Pattern int sum = 0; for(int i=0; i<n; i++) sum += array[i]; Search Pattern for(int i=0; i<n; i++) { if(found) break; } Validation Pattern do { cin >> input; } while(!valid); Menu Pattern do { showMenu(); } while(choice != exit);

Challenge Exercise: Pattern Printer

🏋️ Advanced Loop Challenge

Create a program that prints these patterns using nested loops:

Pattern 1:        Pattern 2:        Pattern 3:
*                 * * * * *         1
* *               * * * *           2 3
* * *             * * *             4 5 6
* * * *           * *               7 8 9 10
* * * * *         *                 11 12 13 14 15
💡 Hint

Use nested loops where the inner loop runs from 0 to i

✅ Solution
for (int i = 1; i <= 5; i++) {
    for (int j = 1; j <= i; j++) {
        cout << "* ";
    }
    cout << '\n';
}

Real-World Application: Grade Calculator

// Calculate class average with input validation
int numStudents;
double total = 0;
double grade;

// Get number of students with validation
do {
    cout << "How many students? (1-50): ";
    cin >> numStudents;
} while (numStudents < 1 || numStudents > 50);

// Input grades for each student
for (int i = 1; i <= numStudents; i++) {
    do {
        cout << "Enter grade for student " << i << " (0-100): ";
        cin >> grade;

        if (grade < 0 || grade > 100) {
            cout << "Invalid grade! Try again." << '\n';
        }
    } while (grade < 0 || grade > 100);

    total += grade;
}

// Calculate and display average
double average = total / numStudents;
cout << "\nClass average: " << average << '\n';

// Determine class performance
if (average >= 90) {
    cout << "Outstanding class performance!" << '\n';
} else if (average >= 80) {
    cout << "Good class performance." << '\n';
} else if (average >= 70) {
    cout << "Satisfactory performance." << '\n';
} else {
    cout << "Class needs improvement." << '\n';
}

Loop Performance Tips

🎯 Quick Quiz

Question 1: What is the key difference between a while loop and a do-while loop?

Question 2: In for (int i = 1; i <= 10; i++) { if (i % 2 == 0) continue; cout << i << " "; }, what happens when i is even?

Question 3: Given int x = 10;, how many times does while (x < 5) { cout << x; } print, compared to do { cout << x; } while (x < 5);?

Summary

🎉 Key Takeaways

  • FOR loops are best when you know the exact number of iterations
  • WHILE loops are perfect for condition-based repetition
  • DO-WHILE loops guarantee at least one execution
  • break exits the loop entirely, continue skips to the next iteration
  • Nested loops are powerful but can be complex - trace through them carefully
  • Always ensure your loops will eventually end - avoid infinite loops!
  • Choose the right loop for the task to make your code clearer
graph LR A[Master Loops] --> B[Automate Tasks] B --> C[Process Data] C --> D[Build Complex Programs] D --> E[Become Efficient Programmer!]

📚 Additional Resources

🚀 What's Next?

You can now automate repetition with for, while, and do-while loops, and steer their flow with break and continue. Next, in Lesson 6: Arrays and Strings, you'll put those loops straight to work — iterating over collections of data, walking character arrays, and building the data-structure instincts every C++ program depends on.

🎉 Loop mastery achieved!

You just learned the tool that powers almost every real program - from processing files to running game loops. Keep practicing, and reaching for the right loop will become second nature.