Coming Soon

This lesson is currently being developed

Introduction to loops and while statements

Master repetitive execution with while loops.

Control Flow
Chapter
Beginner
Difficulty
45min
Estimated Time

What to Expect

Comprehensive explanations with practical examples

Interactive coding exercises to practice concepts

Knowledge quiz to test your understanding

Step-by-step guidance for beginners

Development Status

In Progress

Content is being carefully crafted to provide the best learning experience

Preview

Early Preview Content

This content is still being developed and may change before publication.

8.8 — Introduction to loops and while statements

In this lesson, you'll learn about loops - one of the most powerful control flow features in programming. You'll master while loops, understand when to use them, and discover how they can make your programs more efficient and elegant.

What are loops?

A loop is a control flow statement that repeatedly executes a block of code as long as a specified condition is true. Loops eliminate the need to write repetitive code and are essential for many programming tasks.

Instead of writing:

std::cout << "Hello\n";
std::cout << "Hello\n";
std::cout << "Hello\n";
std::cout << "Hello\n";
std::cout << "Hello\n";

You can write:

int count = 0;
while (count < 5)
{
    std::cout << "Hello\n";
    ++count;
}

The while loop

A while loop repeatedly executes a block of code as long as its condition remains true.

Syntax:

while (condition)
{
    // Code to execute repeatedly
    // Remember to modify the condition variable!
}

Flow:

  1. Check the condition
  2. If true, execute the loop body
  3. Return to step 1
  4. If false, skip the loop and continue after it

Basic while loop example

#include <iostream>

int main()
{
    int count = 1;
    
    while (count <= 5)
    {
        std::cout << "Count: " << count << std::endl;
        ++count;  // IMPORTANT: Modify the loop variable
    }
    
    std::cout << "Loop finished!" << std::endl;
    
    return 0;
}

Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Loop finished!

Loop components

Every well-formed loop has three essential components:

1. Initialization

Set up the loop control variable before the loop:

int i = 0;  // Initialize loop variable

2. Condition

Test that determines whether to continue looping:

while (i < 10)  // Condition to check each iteration

3. Update

Modify the loop variable to eventually make the condition false:

++i;  // Update loop variable

Complete example with all components

#include <iostream>

int main()
{
    // 1. Initialization
    int i = 0;
    
    // 2. Condition
    while (i < 3)
    {
        std::cout << "Iteration " << i << std::endl;
        
        // 3. Update (CRITICAL - prevents infinite loop)
        ++i;
    }
    
    return 0;
}

Output:

Iteration 0
Iteration 1
Iteration 2

Common while loop patterns

Pattern 1: Counting up

#include <iostream>

int main()
{
    int num = 1;
    
    while (num <= 10)
    {
        std::cout << num << " ";
        ++num;
    }
    std::cout << std::endl;
    
    return 0;
}

Output:

1 2 3 4 5 6 7 8 9 10 

Pattern 2: Counting down

#include <iostream>

int main()
{
    int countdown = 5;
    
    while (countdown > 0)
    {
        std::cout << "T-minus " << countdown << "...\n";
        --countdown;
    }
    
    std::cout << "Blast off! 🚀\n";
    
    return 0;
}

Output:

T-minus 5...
T-minus 4...
T-minus 3...
T-minus 2...
T-minus 1...
Blast off! 🚀

Pattern 3: Input validation

#include <iostream>

int main()
{
    int number;
    
    std::cout << "Enter a number between 1 and 10: ";
    std::cin >> number;
    
    while (number < 1 || number > 10)
    {
        std::cout << "Invalid input! Enter a number between 1 and 10: ";
        std::cin >> number;
    }
    
    std::cout << "Thank you! You entered: " << number << std::endl;
    
    return 0;
}

Sample Output:

Enter a number between 1 and 10: 15
Invalid input! Enter a number between 1 and 10: -3
Invalid input! Enter a number between 1 and 10: 7
Thank you! You entered: 7

Pattern 4: Menu-driven program

#include <iostream>

int main()
{
    int choice = 0;
    
    while (choice != 4)
    {
        std::cout << "\n=== MENU ===\n";
        std::cout << "1. Say Hello\n";
        std::cout << "2. Calculate Square\n";
        std::cout << "3. Show Time\n";
        std::cout << "4. Exit\n";
        std::cout << "Choose an option: ";
        
        std::cin >> choice;
        
        if (choice == 1)
        {
            std::cout << "Hello, World!\n";
        }
        else if (choice == 2)
        {
            int number;
            std::cout << "Enter a number: ";
            std::cin >> number;
            std::cout << number << " squared is " << (number * number) << std::endl;
        }
        else if (choice == 3)
        {
            std::cout << "It's programming time!\n";
        }
        else if (choice == 4)
        {
            std::cout << "Goodbye!\n";
        }
        else
        {
            std::cout << "Invalid choice. Please try again.\n";
        }
    }
    
    return 0;
}

Practical examples

Example 1: Sum of numbers

#include <iostream>

int main()
{
    int n, sum = 0, i = 1;
    
    std::cout << "Enter a positive integer: ";
    std::cin >> n;
    
    while (i <= n)
    {
        sum += i;  // Add current number to sum
        ++i;       // Move to next number
    }
    
    std::cout << "Sum of numbers from 1 to " << n << " is: " << sum << std::endl;
    
    return 0;
}

Sample Output:

Enter a positive integer: 5
Sum of numbers from 1 to 5 is: 15

(1 + 2 + 3 + 4 + 5 = 15)

Example 2: Factorial calculation

#include <iostream>

int main()
{
    int n, factorial = 1, i = 1;
    
    std::cout << "Enter a positive integer: ";
    std::cin >> n;
    
    if (n < 0)
    {
        std::cout << "Factorial is not defined for negative numbers.\n";
        return 1;
    }
    
    while (i <= n)
    {
        factorial *= i;  // Multiply by current number
        ++i;             // Move to next number
    }
    
    std::cout << n << "! = " << factorial << std::endl;
    
    return 0;
}

Sample Output:

Enter a positive integer: 6
6! = 720

(6! = 6 × 5 × 4 × 3 × 2 × 1 = 720)

Example 3: Digit counter

#include <iostream>

int main()
{
    int number, digits = 0;
    
    std::cout << "Enter a number: ";
    std::cin >> number;
    
    // Handle special case of 0
    if (number == 0)
    {
        digits = 1;
    }
    else
    {
        // Make number positive for counting
        if (number < 0)
        {
            number = -number;
        }
        
        while (number > 0)
        {
            number /= 10;  // Remove last digit
            ++digits;      // Count the removed digit
        }
    }
    
    std::cout << "Number of digits: " << digits << std::endl;
    
    return 0;
}

Sample Output:

Enter a number: 12345
Number of digits: 5

Example 4: Number guessing game

#include <iostream>

int main()
{
    int secretNumber = 42;
    int guess;
    bool hasGuessed = false;
    
    std::cout << "Welcome to the Number Guessing Game!\n";
    std::cout << "I'm thinking of a number between 1 and 100.\n";
    
    while (!hasGuessed)
    {
        std::cout << "Enter your guess: ";
        std::cin >> guess;
        
        if (guess == secretNumber)
        {
            std::cout << "Congratulations! You guessed it!\n";
            hasGuessed = true;
        }
        else if (guess < secretNumber)
        {
            std::cout << "Too low! Try again.\n";
        }
        else
        {
            std::cout << "Too high! Try again.\n";
        }
    }
    
    return 0;
}

Sample Output:

Welcome to the Number Guessing Game!
I'm thinking of a number between 1 and 100.
Enter your guess: 50
Too high! Try again.
Enter your guess: 25
Too low! Try again.
Enter your guess: 42
Congratulations! You guessed it!

Infinite loops (and how to avoid them)

An infinite loop runs forever because the condition never becomes false.

Dangerous: Infinite loop

#include <iostream>

int main()
{
    int i = 1;
    
    while (i <= 10)
    {
        std::cout << "i = " << i << std::endl;
        // BUG: Forgot to increment i!
    }
    
    return 0;  // This line is never reached
}

This prints "i = 1" forever because i is never modified.

Safe: Proper loop termination

#include <iostream>

int main()
{
    int i = 1;
    
    while (i <= 10)
    {
        std::cout << "i = " << i << std::endl;
        ++i;  // IMPORTANT: Increment i to eventually exit loop
    }
    
    return 0;
}

Intentional infinite loop (with break)

Sometimes you want a loop that runs indefinitely until a specific condition is met:

#include <iostream>

int main()
{
    while (true)  // Intentional infinite loop
    {
        char choice;
        std::cout << "Continue? (y/n): ";
        std::cin >> choice;
        
        if (choice == 'n' || choice == 'N')
        {
            break;  // Exit the infinite loop
        }
        
        std::cout << "Continuing...\n";
    }
    
    std::cout << "Program ended.\n";
    
    return 0;
}

While loop variations

Using boolean variables

#include <iostream>

int main()
{
    bool keepPlaying = true;
    int score = 0;
    
    while (keepPlaying)
    {
        char action;
        std::cout << "Current score: " << score << std::endl;
        std::cout << "Action - (p)lay, (q)uit: ";
        std::cin >> action;
        
        if (action == 'p')
        {
            score += 10;
            std::cout << "You gained 10 points!\n";
        }
        else if (action == 'q')
        {
            keepPlaying = false;  // This will end the loop
        }
        else
        {
            std::cout << "Invalid action!\n";
        }
    }
    
    std::cout << "Final score: " << score << std::endl;
    
    return 0;
}

Complex conditions

#include <iostream>

int main()
{
    int attempts = 0;
    int maxAttempts = 3;
    bool success = false;
    
    while (attempts < maxAttempts && !success)
    {
        std::cout << "Attempt " << (attempts + 1) << " of " << maxAttempts << std::endl;
        
        std::string password;
        std::cout << "Enter password: ";
        std::cin >> password;
        
        if (password == "secret123")
        {
            success = true;
            std::cout << "Access granted!\n";
        }
        else
        {
            std::cout << "Wrong password!\n";
            ++attempts;
        }
    }
    
    if (!success)
    {
        std::cout << "Access denied. Too many failed attempts.\n";
    }
    
    return 0;
}

Loop design best practices

1. Always initialize loop variables

// Good
int i = 0;  // Clearly initialized
while (i < 10) { /* ... */ ++i; }

// Bad
int i;      // Uninitialized - contains garbage
while (i < 10) { /* ... */ ++i; }  // Undefined behavior

2. Make sure the condition can become false

// Good - condition will eventually become false
int count = 10;
while (count > 0)
{
    std::cout << count << " ";
    --count;  // This makes count eventually reach 0
}

// Bad - condition never changes
int count = 10;
while (count > 0)
{
    std::cout << count << " ";
    // Missing: --count; - infinite loop!
}

3. Update loop variables at consistent locations

// Good - update at end of loop body
while (condition)
{
    // Do work
    ++counter;  // Consistent location
}

// Less clear - updates scattered
while (condition)
{
    ++counter;  // Update here?
    // Do some work
    if (something)
        ++counter;  // And here too?
    // More work
}

4. Use meaningful variable names

// Good - clear intent
int studentCount = 0;
while (studentCount < totalStudents)
{
    processStudent(studentCount);
    ++studentCount;
}

// Less clear
int i = 0;
while (i < n)
{
    processStudent(i);
    ++i;
}

When to use while loops

Use while loops when:

  • You don't know exactly how many iterations you need
  • The loop should continue until a specific condition is met
  • You're doing input validation
  • You're implementing menu systems
  • The termination condition is complex

Examples where while is perfect:

  • Reading user input until valid
  • Processing data until end-of-file
  • Game loops that run until game over
  • Server loops that handle requests until shutdown

Summary

While loops provide powerful repetition control:

Structure:

  • Initialization: Set up loop control variables
  • Condition: Test evaluated before each iteration
  • Update: Modify variables to eventually terminate loop

Key concepts:

  • Loop executes while condition is true
  • Condition checked before each iteration
  • Must modify loop variables to avoid infinite loops
  • Useful when iteration count is unknown

Common patterns:

  • Counting (up or down)
  • Input validation
  • Menu-driven programs
  • Accumulation (sums, products)
  • Search operations

Best practices:

  • Always initialize loop variables
  • Ensure condition can become false
  • Update variables consistently
  • Use meaningful names
  • Avoid infinite loops (unless intentional with break)

While loops are fundamental to programming and essential for creating responsive, interactive programs.

Quiz

  1. What are the three essential components of a well-formed loop?
  2. When is the condition in a while loop evaluated?
  3. What happens if you forget to update the loop control variable?
  4. What's the difference between ++i and i++ in a loop?
  5. How can you create an intentional infinite loop that can still be exited?

Practice exercises

  1. Multiplication table: Write a program that prints the multiplication table for a number entered by the user (e.g., for 5: 5×1=5, 5×2=10, etc., up to 5×12=60).

  2. Power calculator: Create a program that calculates x^n (x to the power of n) using a while loop (don't use built-in power functions).

  3. Palindrome checker: Write a program that checks if a number is a palindrome (reads the same forwards and backwards) using a while loop to reverse the digits.

  4. Simple ATM: Design a simple ATM system with a menu that allows users to check balance, deposit, withdraw, and exit. Use a while loop to keep the program running until the user chooses to exit.

Continue Learning

Explore other available lessons while this one is being prepared.

View Course

Explore More Courses

Discover other available courses while this lesson is being prepared.

Browse Courses

Lesson Discussion

Share your thoughts and questions

💬

No comments yet. Be the first to share your thoughts!

Sign in to join the discussion