C++ do-while Loop

Introduction

The do-while loop in C++ is a control flow statement that allows code to be executed repeatedly based on a given condition. Unlike the while loop, the do-while loop guarantees that the loop body is executed at least once before the condition is tested. This makes the do-while loop particularly useful for scenarios where the code needs to run at least once regardless of the condition.

Syntax

The basic syntax of a do-while loop is as follows:

do {
    // code to be executed
} while (condition);

Key Points

  • Loop Body: The block of code that is executed once before the condition is tested.
  • Condition: Evaluated after each iteration. If true, the loop body is executed again. If false, the loop terminates.

Example: Basic do-while Loop

#include <iostream>
using namespace std;

int main() {
    int i = 0; // Initialization of loop control variable

    do {
        cout << "i = " << i << endl; // Print the value of i
        i++; // Increment the loop control variable
    } while (i < 5); // Condition

    return 0;
}

Output

i = 0
i = 1
i = 2
i = 3
i = 4

Explanation

  • Initialization: int i = 0 initializes the loop control variable i to 0.
  • Loop Body: cout << "i = " << i << endl; prints the value of i, and i++ increments i by 1.
  • Condition: i < 5 checks if i is less than 5. If true, the loop body executes again. If false, the loop terminates.

Example: Sum of First N Natural Numbers

A do-while loop can be used to calculate the sum of the first N natural numbers.

#include <iostream>
using namespace std;

int main() {
    int n, sum = 0, i = 1; // Initialization of variables

    cout << "Enter a positive integer: ";
    cin >> n; // Input the value of n

    do {
        sum += i; // Add i to sum
        i++; // Increment i
    } while (i <= n); // Condition

    cout << "Sum of the first " << n << " natural numbers is: " << sum << endl;

    return 0;
}

Output

Enter a positive integer: 10
Sum of the first 10 natural numbers is: 55

Explanation

  • Initialization: int n, sum = 0, i = 1 initializes the variables.
  • Input: cin >> n takes the input value of n.
  • Loop Body: sum += i adds i to sum, and i++ increments i by 1.
  • Condition: i <= n checks if i is less than or equal to n. If true, the loop body executes again. If false, the loop terminates.

Example: Input Validation

A do-while loop can be used to repeatedly prompt the user for input until a valid value is entered.

#include <iostream>
using namespace std;

int main() {
    int number; // Variable to store user input

    do {
        cout << "Enter a positive integer: ";
        cin >> number; // Input the value of number

        if (number <= 0) {
            cout << "Invalid input. Please try again." << endl;
        }
    } while (number <= 0); // Condition

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

    return 0;
}

Output

Enter a positive integer: -5
Invalid input. Please try again.
Enter a positive integer: 0
Invalid input. Please try again.
Enter a positive integer: 7
You entered a valid number: 7

Explanation

  • Initialization: int number initializes the variable to store user input.
  • Loop Body: cin >> number takes the input value of number. If the input is invalid (number <= 0), an error message is displayed.
  • Condition: number <= 0 checks if the input is invalid. If true, the loop body executes again. If false, the loop terminates.

Example: Reverse Digits of a Number

A do-while loop can be used to reverse the digits of a given number.

#include <iostream>
using namespace std;

int main() {
    int number, reversedNumber = 0; // Initialization of variables

    cout << "Enter an integer: ";
    cin >> number; // Input the value of number

    do {
        int remainder = number % 10; // Get the last digit
        reversedNumber = reversedNumber * 10 + remainder; // Build the reversed number
        number /= 10; // Remove the last digit
    } while (number != 0); // Condition

    cout << "Reversed Number: " << reversedNumber << endl;

    return 0;
}

Output

Enter an integer: 1234
Reversed Number: 4321

Explanation

  • Initialization: int number, reversedNumber = 0 initializes the variables.
  • Input: cin >> number takes the input value of number.
  • Loop Body:
    • int remainder = number % 10 gets the last digit of number.
    • reversedNumber = reversedNumber * 10 + remainder builds the reversed number.
    • number /= 10 removes the last digit from number.
  • Condition: number != 0 checks if number is not equal to 0. If true, the loop body executes again. If false, the loop terminates.

Conclusion

The do-while loop is a powerful and flexible control flow statement in C++ that allows you to execute a block of code repeatedly based on a given condition. Unlike the while loop, the do-while loop ensures that the loop body is executed at least once before the condition is tested. This chapter covered the basic syntax of the do-while loop, examples of calculating the sum of the first N natural numbers, validating user input, and reversing the digits of a number. Understanding how to use the do-while loop effectively will help you write more efficient and readable code. In the next chapter, we will explore the break statement in C++.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top