Lesson 30 of 60 – do-while Loop in C++
50%

do-while Loop in C++

The do-while loop is used to execute a block of code repeatedly while a specified condition is true. The main difference between a while loop and a do-while loop is that the do-while loop executes its body at least once.

Note: In a do-while loop, the condition is checked after the loop body executes. Therefore, even when the condition is initially false, the loop body runs once.

1. What is a do-while Loop?

A do-while loop executes a block of code first and then checks the condition.

do {
    // statements
} while (condition);

The semicolon after the condition is required.

2. Syntax of do-while Loop

do {

    // code to execute

} while (condition);

The do block contains the statements to execute, and the while condition determines whether the loop should repeat.

3. Simple do-while Example

int i = 1;

do {

    std::cout << i << std::endl;

    i++;

} while (i <= 5);

Output:

1
2
3
4
5

4. How do-while Works

A do-while loop works in this order:

  1. The loop body executes.
  2. The condition is checked.
  3. If the condition is true, the loop repeats.
  4. If the condition is false, the loop stops.
do {
    // execute first
} while (condition);

5. do-while Executes at Least Once

int number = 10;

do {

    std::cout << "Hello";

} while (number < 5);

The condition is false because 10 is not less than 5, but Hello is still printed once.

6. while vs do-while

while Loop do-while Loop
Checks condition before executing the body. Checks condition after executing the body.
May execute zero times. Executes at least once.
No semicolon after the condition. Semicolon is required after the while condition.

7. Printing Numbers from 1 to 5

int i = 1;

do {

    std::cout << i << std::endl;

    i++;

} while (i <= 5);

The loop prints the numbers from 1 to 5.

8. Printing Numbers from 5 to 1

int i = 5;

do {

    std::cout << i << std::endl;

    i--;

} while (i >= 1);

The loop counts backward from 5 to 1.

9. Printing Even Numbers

int i = 2;

do {

    std::cout << i << std::endl;

    i += 2;

} while (i <= 20);

The loop prints even numbers from 2 to 20.

10. Printing Odd Numbers

int i = 1;

do {

    std::cout << i << std::endl;

    i += 2;

} while (i <= 19);

The loop prints odd numbers from 1 to 19.

11. do-while with User Input

#include <iostream>

int main() {

    int number;

    do {

        std::cout << "Enter a positive number: ";
        std::cin >> number;

    } while (number <= 0);

    std::cout << "Valid number entered";

    return 0;
}

The user is asked for input at least once.

12. Input Validation

The do-while loop is useful when input must be entered at least once and needs to satisfy a condition.

int marks;

do {

    std::cout << "Enter marks between 0 and 100: ";
    std::cin >> marks;

} while (marks < 0 || marks > 100);

std::cout << "Valid marks";

13. do-while with if Statement

int i = 1;

do {

    if (i % 2 == 0) {
        std::cout << i
                  << " is even"
                  << std::endl;
    }

    i++;

} while (i <= 10);

The if statement checks each number generated by the loop.

14. Sum Using do-while

int i = 1;
int sum = 0;

do {

    sum += i;

    i++;

} while (i <= 10);

std::cout << "Sum = " << sum;

The program calculates the sum of numbers from 1 to 10.

15. Multiplication Table

int number = 5;
int i = 1;

do {

    std::cout << number
              << " x "
              << i
              << " = "
              << number * i
              << std::endl;

    i++;

} while (i <= 10);

This program prints the multiplication table of 5.

16. Factorial Using do-while

int number = 5;
int factorial = 1;
int i = 1;

do {

    factorial *= i;

    i++;

} while (i <= number);

std::cout << "Factorial = "
          << factorial;

The factorial of 5 is 120.

17. Menu Using do-while

int choice;

do {

    std::cout << "1. Add" << std::endl;
    std::cout << "2. View" << std::endl;
    std::cout << "3. Exit" << std::endl;

    std::cout << "Enter choice: ";
    std::cin >> choice;

} while (choice != 3);

The menu appears at least once and continues until the user chooses 3.

18. Complete Menu Example

#include <iostream>

int main() {

    int choice;

    do {

        std::cout << std::endl;
        std::cout << "1. Add Student" << std::endl;
        std::cout << "2. View Student" << std::endl;
        std::cout << "3. Exit" << std::endl;

        std::cout << "Enter choice: ";
        std::cin >> choice;

        if (choice == 1) {
            std::cout << "Add Student selected";
        }
        else if (choice == 2) {
            std::cout << "View Student selected";
        }
        else if (choice == 3) {
            std::cout << "Exiting...";
        }
        else {
            std::cout << "Invalid choice";
        }

    } while (choice != 3);

    return 0;
}

19. Using break in do-while

The break statement can immediately terminate a do-while loop.

int i = 1;

do {

    if (i == 5) {
        break;
    }

    std::cout << i << std::endl;

    i++;

} while (i <= 10);

The loop stops when i becomes 5.

20. Using continue in do-while

The continue statement skips the remaining part of the current iteration. In a do-while loop, execution then proceeds to the condition check.

int i = 0;

do {

    i++;

    if (i == 3) {
        continue;
    }

    std::cout << i << std::endl;

} while (i < 5);

The number 3 is skipped.

21. do-while with Password Validation

#include <iostream>
#include <string>

int main() {

    std::string password;

    do {

        std::cout << "Enter password: ";
        std::cin >> password;

        if (password != "1234") {
            std::cout << "Wrong password"
                      << std::endl;
        }

    } while (password != "1234");

    std::cout << "Correct password";

    return 0;
}

22. do-while with Character Input

char answer;

do {

    std::cout << "Continue? (y/n): ";
    std::cin >> answer;

} while (answer != 'n');

std::cout << "Program ended";

The question is displayed at least once and repeats until the user enters n.

23. do-while with Multiple Conditions

int number;

do {

    std::cout << "Enter a number between 1 and 100: ";
    std::cin >> number;

} while (number < 1 || number > 100);

std::cout << "Valid number";

The loop continues while the number is outside the valid range.

24. do-while vs while Example

while loop:

int number = 10;

while (number < 5) {
    std::cout << "Hello";
}

Here, the condition is false initially, so nothing is printed.

do-while loop:

int number = 10;

do {
    std::cout << "Hello";
} while (number < 5);

Here, Hello is printed once because the condition is checked after the loop body.

25. Nested do-while Loop

A do-while loop can be placed inside another do-while loop.

int i = 1;

do {

    int j = 1;

    do {

        std::cout << i
                  << ","
                  << j
                  << std::endl;

        j++;

    } while (j <= 3);

    i++;

} while (i <= 3);

26. Common do-while Mistakes

  • Forgetting the semicolon after while (condition).
  • Forgetting to update the loop variable.
  • Writing an incorrect stopping condition.
  • Creating an accidental infinite loop.
  • Confusing do-while with while.
  • Forgetting that the body executes at least once.
  • Using continue without considering the condition check.

Correct syntax:

do {
    // statements
} while (condition);

27. Practical Student Marks Validation

#include <iostream>

int main() {

    int marks;

    do {

        std::cout << "Enter marks between 0 and 100: ";
        std::cin >> marks;

        if (marks < 0 || marks > 100) {
            std::cout << "Invalid marks"
                      << std::endl;
        }

    } while (marks < 0 || marks > 100);

    std::cout << "Marks accepted: "
              << marks;

    return 0;
}

28. Practical ATM Menu

#include <iostream>

int main() {

    int choice;

    do {

        std::cout << std::endl;
        std::cout << "1. Check Balance" << std::endl;
        std::cout << "2. Deposit" << std::endl;
        std::cout << "3. Withdraw" << std::endl;
        std::cout << "4. Exit" << std::endl;

        std::cout << "Enter choice: ";
        std::cin >> choice;

        switch (choice) {

            case 1:
                std::cout << "Balance selected";
                break;

            case 2:
                std::cout << "Deposit selected";
                break;

            case 3:
                std::cout << "Withdraw selected";
                break;

            case 4:
                std::cout << "Exiting...";
                break;

            default:
                std::cout << "Invalid choice";
        }

    } while (choice != 4);

    return 0;
}

29. Best Practices for do-while

  • Use do-while when the loop body must execute at least once.
  • Keep the stopping condition clear.
  • Update the loop variable when using a counter.
  • Use input validation carefully.
  • Use break only when it makes the logic clearer.
  • Remember the semicolon after the while condition.
  • Use proper indentation.
  • Avoid unnecessary nesting.
do {

    // statements

} while (condition);

30. do-while Loop – Final Summary

Part Purpose
do Starts the loop body.
Loop Body Executes before the condition is checked.
while Checks whether another iteration should execute.
Condition Controls whether the loop repeats.
break Terminates the loop immediately.
continue Skips the remaining part of the current iteration and proceeds to the condition check.
do {

    // statements

} while (condition);

📌 Key Points

  • The do-while loop executes its body before checking the condition.
  • A do-while loop executes at least once.
  • The condition is checked after each iteration.
  • A semicolon is required after the while condition.
  • Do-while loops are useful for input validation.
  • They are useful for menu-driven programs.
  • break can terminate the loop immediately.
  • continue skips the remaining statements of the current iteration and proceeds to the condition check.
  • The loop variable should be updated when necessary.
  • Do-while loops can contain if statements and other loops.

🧠 Quick Quiz

Question: What is the main difference between a while loop and a do-while loop?