C++ while and do...while loops


Introduction

In C++, the while and do...while loops are two fundamental control flow structures that allow you to repeat a block of code based on a specified condition. While both loops are used for repetition, there is a key difference between them in terms of when the condition is evaluated.

In this blog post, we'll cover:

  • The syntax and use cases for the while loop.
  • The syntax and use cases for the do...while loop.
  • Differences between the two loops and practical examples of each.

1. The while Loop in C++

The while loop is used when you want to repeat a block of code as long as a specified condition is true. It first checks the condition and then executes the block of code. If the condition is false initially, the code inside the while loop will not execute.

Syntax:

while (condition) {
    // Code to execute
}
  • Condition: This part is evaluated before the loop starts. If it is true, the loop continues to execute. If it is false, the loop terminates.

Example 1: Printing Numbers from 1 to 5

#include <iostream>
using namespace std;

int main() {
    int i = 1;

    // Print numbers from 1 to 5 using while loop
    while (i <= 5) {
        cout << "Number: " << i << endl;
        i++;  // Increment the counter
    }

    return 0;
}

Output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

Explanation:

  • Initialization: i = 1 initializes the loop counter.
  • Condition: The condition i <= 5 ensures that the loop continues as long as i is less than or equal to 5.
  • Increment: i++ increments the value of i after each iteration.

2. The do...while Loop in C++

The do...while loop is similar to the while loop, but with one key difference: the condition is checked after the code block is executed. This means that the block of code will always execute at least once, regardless of whether the condition is initially true or false.

Syntax:

do {
    // Code to execute
} while (condition);
  • Condition: This part is evaluated after the loop executes. If it is true, the loop continues to execute. If it is false, the loop terminates.

Example 2: Printing Numbers from 1 to 5 Using do...while

#include <iostream>
using namespace std;

int main() {
    int i = 1;

    // Print numbers from 1 to 5 using do...while loop
    do {
        cout << "Number: " << i << endl;
        i++;  // Increment the counter
    } while (i <= 5);

    return 0;
}

Output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

Explanation:

  • Initialization: i = 1 initializes the loop counter.
  • Code Execution: The code inside the loop executes at least once, even before checking the condition.
  • Condition: After the first execution, the condition i <= 5 is evaluated, and if it is true, the loop continues.

3. Key Differences Between while and do...while Loops

Aspect while loop do...while loop
Condition check Condition is checked before the loop runs. Condition is checked after the loop runs.
Guaranteed execution Code inside the loop might not execute if the condition is false initially. Code inside the loop is guaranteed to execute at least once.
Common use case When you want to repeat code only if the condition is initially true. When you want to execute the loop code at least once regardless of the condition.

4. Example 3: User Input Validation Using while Loop

You can use a while loop for repeatedly asking for user input until a valid input is provided.

Example: Repeatedly Asking for a Positive Number

#include <iostream>
using namespace std;

int main() {
    int num;

    // Ask the user to input a positive number
    cout << "Enter a positive number: ";
    cin >> num;

    // Continue asking until the user enters a positive number
    while (num <= 0) {
        cout << "Invalid input! Please enter a positive number: ";
        cin >> num;
    }

    cout << "You entered a positive number: " << num << endl;

    return 0;
}

Output:

Enter a positive number: -3
Invalid input! Please enter a positive number: 5
You entered a positive number: 5

Explanation:

  • The while loop checks if the user enters a number less than or equal to zero and continues prompting for a valid input until a positive number is entered.

5. Example 4: Infinite Loop with do...while

A do...while loop is useful for scenarios where you want to ensure the loop executes at least once, such as a menu-based system where the user can choose to continue or exit after each operation.

Example: Simple Menu System

#include <iostream>
using namespace std;

int main() {
    int choice;

    do {
        cout << "Menu:\n";
        cout << "1. Print Hello\n";
        cout << "2. Exit\n";
        cout << "Enter your choice: ";
        cin >> choice;

        if (choice == 1) {
            cout << "Hello, World!" << endl;
        } else if (choice == 2) {
            cout << "Exiting program." << endl;
        } else {
            cout << "Invalid choice! Try again.\n";
        }
    } while (choice != 2);  // Continue until the user chooses to exit

    return 0;
}

Output:

Menu:
1. Print Hello
2. Exit
Enter your choice: 1
Hello, World!
Menu:
1. Print Hello
2. Exit
Enter your choice: 2
Exiting program.

Explanation:

  • The loop ensures the user sees the menu and can interact with it. If the user chooses an invalid option, the loop continues, and the user is prompted again until they select option 2 to exit.

6. Example 5: Breaking Out of a while Loop Early

In both while and do...while loops, you can use the break statement to terminate the loop before the condition becomes false.

Example: Finding the First Negative Number

#include <iostream>
using namespace std;

int main() {
    int arr[] = {5, 8, 10, -2, 7};
    int length = 5;

    int i = 0;
    while (i < length) {
        if (arr[i] < 0) {
            cout << "First negative number: " << arr[i] << endl;
            break;  // Exit the loop after finding the negative number
        }
        i++;
    }

    return 0;
}

Output:

First negative number: -2

Explanation:

  • The while loop iterates through the array. When it finds the first negative number, it prints it and then breaks out of the loop.