Home C++ do-while loop in C++ tutorial with code examples

do-while loop in C++ tutorial with code examples

The do-while loop in C++ is a control flow statement that executes a block of code at least once and then repeatedly executes it as long as a given condition is true.

Unlike the while loop, a do-while loop checks the condition after the code block is executed, ensuring that the loop runs at least once.

Syntax of do-while Loop

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

1. Basic Example of do-while Loop

In this example, the loop will print numbers from 1 to 5.

#include <iostream>
using namespace std;

int main() {
    int i = 1;

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

    return 0;
}

Explanation:

  • The do block executes, printing i and incrementing it.
  • The loop repeats as long as i <= 5.

Output:

1 2 3 4 5

2. Ensuring a Loop Executes at Least Once

Since the do-while loop checks the condition after executing the loop body, it runs at least once, even if the condition is initially false.

#include <iostream>
using namespace std;

int main() {
    int i = 10;

    do {
        cout << "This will print at least once, i = " << i << endl;
        i++;
    } while (i < 10); // Condition is false initially

    return 0;
}

Explanation:

  • Here, i is initially 10, so i < 10 is false.
  • Despite the condition being false, the loop executes once, printing i.

Output:

This will print at least once, i = 10

3. User Input Validation with do-while

The do-while loop is useful for input validation, where you want to prompt the user until they enter valid data.

#include <iostream>
using namespace std;

int main() {
    int number;

    do {
        cout << "Enter a positive number: ";
        cin >> number;
    } while (number <= 0);

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

    return 0;
}

Explanation:

  • The loop keeps prompting the user until they enter a positive number (number > 0).
  • This ensures that number is validated before proceeding.

Output (example):

Enter a positive number: -1
Enter a positive number: 0
Enter a positive number: 5
You entered: 5

4. Summing Numbers Using do-while Loop

This example demonstrates how to sum numbers using a do-while loop.

#include <iostream>
using namespace std;

int main() {
    int sum = 0, number = 1;

    do {
        sum += number;
        number++;
    } while (number <= 5);

    cout << "Sum of numbers from 1 to 5: " << sum << endl;

    return 0;
}

Explanation:

  • The loop adds number to sum and increments number until number is greater than 5.

Output:

Sum of numbers from 1 to 5: 15

5. Calculating Factorial with do-while Loop

This example calculates the factorial of a number using a do-while loop.

#include <iostream>
using namespace std;

int main() {
    int number = 5;
    int factorial = 1;
    int i = 1;

    do {
        factorial *= i;
        i++;
    } while (i <= number);

    cout << "Factorial of " << number << " is: " << factorial << endl;

    return 0;
}

Explanation:

  • factorial *= i multiplies factorial by i in each loop iteration.
  • The loop continues until i exceeds number.

Output:

Factorial of 5 is: 120

6. Working with Arrays in do-while Loop

This example shows how to iterate over an array using a do-while loop.

#include <iostream>
using namespace std;

int main() {
    int numbers[] = {10, 20, 30, 40, 50};
    int length = sizeof(numbers) / sizeof(numbers[0]);
    int i = 0;

    do {
        cout << "Element " << i << ": " << numbers[i] << endl;
        i++;
    } while (i < length);

    return 0;
}

Explanation:

  • i is incremented after each element is printed.
  • The loop continues until i reaches the length of the array.

Output:

Element 0: 10
Element 1: 20
Element 2: 30
Element 3: 40
Element 4: 50

7. Menu-Driven Program with do-while Loop

do-while loops are great for creating menu-driven programs, where the menu should display at least once.

#include <iostream>
using namespace std;

int main() {
    int choice;

    do {
        cout << "\nMenu:\n";
        cout << "1. Option 1\n";
        cout << "2. Option 2\n";
        cout << "3. Exit\n";
        cout << "Enter your choice: ";
        cin >> choice;

        switch (choice) {
            case 1:
                cout << "You chose Option 1\n";
                break;
            case 2:
                cout << "You chose Option 2\n";
                break;
            case 3:
                cout << "Exiting...\n";
                break;
            default:
                cout << "Invalid choice. Please try again.\n";
        }
    } while (choice != 3);

    return 0;
}

Explanation:

  • The menu displays and processes user input until the user chooses 3 to exit.

Output (example):

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

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

8. Infinite do-while Loop

You can create an infinite do-while loop by setting the condition to true. This is useful for continuous processes until an external break occurs.

#include <iostream>
using namespace std;

int main() {
    int i = 1;

    do {
        cout << "Loop iteration: " << i << endl;
        i++;
        if (i > 5) {
            break; // Exit the loop when i > 5
        }
    } while (true);

    return 0;
}

Explanation:

  • The loop runs indefinitely due to the true condition.
  • break exits the loop when i exceeds 5.

Output:

Loop iteration: 1
Loop iteration: 2
Loop iteration: 3
Loop iteration: 4
Loop iteration: 5

9. Using do-while for Calculating Powers

This example calculates a power of a base number using a do-while loop.

#include <iostream>
using namespace std;

int main() {
    int base = 2, exponent = 4;
    int result = 1, i = 1;

    do {
        result *= base;
        i++;
    } while (i <= exponent);

    cout << base << " raised to the power of " << exponent << " is: " << result << endl;

    return 0;
}

Explanation:

  • result *= base multiplies result by base on each iteration.
  • The loop continues until i exceeds exponent.

Output:

2 raised to the power of 4 is: 16

10. Reversing a Number with do-while

This example reverses an integer using a do-while loop.

#include <iostream>
using namespace std;

int main() {
    int number = 1234;
    int reversed = 0;

    do {
        int digit = number % 10;
        reversed = reversed * 10 + digit;
        number /= 10;
    } while (number != 0);

    cout << "Reversed number: " << reversed << endl;

    return 0;
}

Explanation:

  • The loop extracts the last digit of number and adds it to reversed.
  • number is reduced by one digit each time (number /= 10) until all digits are processed.

Output:

Reversed number: 4321

Summary Table of do-while Loop Applications

Example Description
Basic Counter Prints numbers from 1 to 5
Ensuring Single Execution Executes at least once even if condition fails
User Input Validation Keeps prompting until valid input is entered
Summing Numbers Calculates sum of numbers from 1 to 5
Calculating Factorial Computes factorial of a number
Iterating Array Elements Displays elements of an array
Menu-Driven Program Displays a menu until the user chooses to exit
Infinite Loop with Break Creates a loop that exits based on condition
Calculating Powers Raises a number to a specified power
Reversing a Number Reverses digits of an integer

Key Takeaways

  • The do-while loop ensures that the code block executes at least once, regardless of the condition.
  • It’s useful for scenarios like user input validation and menu-driven programs, where at least one execution is required.
  • Infinite loops can be created with do-while by using a condition like true, and a break statement can terminate the loop based on specific conditions.
  • Good practices include ensuring that do-while loops don’t run indefinitely by managing the condition correctly.

 

You may also like