Loops: Teaching Your Program to Repeat Tasks

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
how many times] C --> F[When you have
a condition] D --> G[When you need
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

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 << endl;
    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 ===" << endl;
    cout << "1. Play Game" << endl;
    cout << "2. View Scores" << endl;
    cout << "3. Settings" << endl;
    cout << "4. Exit" << endl;
    cout << "Choose (1-4): ";
    cin >> choice;
    
    switch(choice) {
        case 1:
            cout << "Starting game..." << endl;
            break;
        case 2:
            cout << "High scores..." << endl;
            break;
        case 3:
            cout << "Settings..." << endl;
            break;
        case 4:
            cout << "Goodbye!" << endl;
            break;
        default:
            cout << "Invalid choice!" << endl;
    }
} 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 << endl;
}
/* Output:
* * * * * *
* * * * * *
* * * * * *
* * * * * *
*/

// Multiplication table
for (int i = 1; i <= 5; i++) {
    for (int j = 1; j <= 5; j++) {
        cout << i * j << "\t";
    }
    cout << endl;
}
/* 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 << endl;
        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) {
// Need break!
}"] C --> F["for(;;) {
// Need break!
}"] D --> G["while(x < 10) {
// Forgot x++
}"] 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(0));  // 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!" << endl;
    
    // 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." << endl;
    } else if (guess < secretNumber) {
        cout << "Too low! Try again." << endl;
    } else {
        cout << "Congratulations! You got it!" << endl;
        cout << "It took you " << attempts << " guesses." << endl;
    }
} 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 for Pattern 1

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

Solution for Pattern 1
for (int i = 1; i <= 5; i++) {
    for (int j = 1; j <= i; j++) {
        cout << "* ";
    }
    cout << endl;
}

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." << endl;
        }
    } while (grade < 0 || grade > 100);
    
    total += grade;
}

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

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

Loop Performance Tips

Key Takeaways

graph LR A[Master Loops] --> B[Automate Tasks] B --> C[Process Data] C --> D[Build Complex Programs] D --> E[Become Efficient Programmer!]