C++ Do/While Loop

Welcome to The Coding College! In this tutorial, we’ll explore the do/while loop in C++. This loop guarantees at least one iteration, making it perfect for situations where the loop body must execute before evaluating the condition.

What is a Do/While Loop?

A do/while loop is a post-test loop, meaning the condition is evaluated after the loop body has executed. This ensures the loop executes at least once, regardless of the condition.

Syntax

do {
    // Code to execute
} while (condition);
  • do: Executes the block of code at least once.
  • while: Checks the condition after each execution of the loop body. If the condition is true, the loop repeats.
  • Semicolon: The while statement ends with a semicolon.

Example: Simple Do/While Loop

#include <iostream>
using namespace std;

int main() {
    int i = 1;

    do {
        cout << i << endl;
        i++;
    } while (i <= 5);

    return 0;
}

Output:

1  
2  
3  
4  
5

Key Difference Between While and Do/While

In a while loop, the condition is checked before the loop body executes. In a do/while loop, the condition is checked after the loop body executes.

Example:

#include <iostream>
using namespace std;

int main() {
    int i = 10;

    // While loop
    cout << "While loop:" << endl;
    while (i < 10) {
        cout << i << endl;
    }

    // Do/while loop
    cout << "Do/while loop:" << endl;
    do {
        cout << i << endl;
    } while (i < 10);

    return 0;
}

Output:

While loop:  
Do/while loop:  
10

The while loop doesn’t execute because the condition is false initially, but the do/while loop runs once before checking the condition.

Example: Input Validation

The do/while loop is commonly used for input validation, where the user must provide valid input before the program proceeds.

#include <iostream>
using namespace std;

int main() {
    int number;

    do {
        cout << "Enter a positive number: ";
        cin >> number;

        if (number <= 0) {
            cout << "Invalid input. Try again." << endl;
        }
    } while (number <= 0);

    cout << "You entered: " << number << endl;

    return 0;
}

Output Example:

Enter a positive number: -3  
Invalid input. Try again.  
Enter a positive number: 0  
Invalid input. Try again.  
Enter a positive number: 5  
You entered: 5

Example: Menu-Driven Program

#include <iostream>
using namespace std;

int main() {
    int choice;

    do {
        cout << "Menu:" << endl;
        cout << "1. Option 1" << endl;
        cout << "2. Option 2" << endl;
        cout << "3. Exit" << endl;
        cout << "Enter your choice: ";
        cin >> choice;

        switch (choice) {
            case 1:
                cout << "You selected Option 1." << endl;
                break;
            case 2:
                cout << "You selected Option 2." << endl;
                break;
            case 3:
                cout << "Exiting program." << endl;
                break;
            default:
                cout << "Invalid choice. Try again." << endl;
        }

        cout << endl;
    } while (choice != 3);

    return 0;
}

Output Example:

Menu:  
1. Option 1  
2. Option 2  
3. Exit  
Enter your choice: 1  
You selected Option 1.  

Menu:  
1. Option 1  
2. Option 2  
3. Exit  
Enter your choice: 3  
Exiting program.

Infinite Do/While Loop

If the condition in a do/while loop is always true, it will create an infinite loop.

#include <iostream>
using namespace std;

int main() {
    int i = 1;

    do {
        cout << i << endl;
    } while (true);  // Infinite loop

    return 0;
}

Note: To prevent infinite loops, ensure the condition will eventually become false or use a break statement.

Breaking Out of a Do/While Loop

You can use the break statement to exit a do/while loop based on a condition.

#include <iostream>
using namespace std;

int main() {
    int i = 1;

    do {
        cout << i << endl;

        if (i == 5) {
            break;
        }

        i++;
    } while (true);

    return 0;
}

Output:

1  
2  
3  
4  
5

Common Mistakes with Do/While Loops

  • Forgetting the Semicolon: The while condition must end with a semicolon.
do {
    // Code
} while (condition) // Missing semicolon here causes a compilation error
  • Infinite Loops: Ensure the condition will eventually become false.
  • Logic Errors: Ensure the loop body modifies variables affecting the loop condition.

Summary

  • The do/while loop guarantees at least one execution of the loop body.
  • It’s ideal for scenarios like input validation or menu-driven programs.
  • Always include a condition that can terminate the loop or use a break statement for control.

Explore More at The Coding College

Learn more about programming concepts at The Coding College. Master C++ with our user-focused, hands-on tutorials designed to help you become a coding expert.

What’s Next?

  • Learn about the for loop, a structured loop for fixed iterations.
  • Dive into nested loops for advanced use cases.
  • Explore arrays and how loops can work with them efficiently.

Leave a Comment