7.8 — Do while statements

Consider the case where we want to show the user a menu and ask them to make a selection -- and if the user chooses an invalid selection, to ask them again. Clearly the menu and selection should go inside a loop of some kind (so we can keep asking the user until they enter valid input), but what kind of loop should we choose?

Since a while loop evaluates the condition up front, it’s an awkward choice. We could solve the issue like this:

But this only works because our initial value of 0 for selection isn’t in the set of valid values (1, 2, 3 or 4). What if 0 was a valid choice? We’d have to pick a different initializer to represent “invalid” -- and now we’re introducing magic numbers (4.13 -- Literals) into our code.

We could instead add a new variable to track validity, like so:

While this avoids the magic number, it introduces a new variable just to ensure the loop runs once, and that adds complexity and the possibility of additional errors.

Do while statements

To help solve problems like the above, C++ offers the do-while statement:

while (condition);

A do while statement is a looping construct that works just like a while loop, except the statement always executes at least once. After the statement has been executed, the do-while loop checks the condition. If the condition evaluates to true, the path of execution jumps back to the top of the do-while loop and executes it again.

Here is our example above using a do-while loop instead of a while loop:

In this way, we’ve avoided both magic numbers and additional variables.

One things worth discussing in the above example is that the selection variable must be declared outside of the do block. If the selection variable were to be declared inside the do block, it would be destroyed when the do block terminates, which happens before the conditional is evaluated. But we need the variable in the while conditional -- consequently, the selection variable must be declared outside the do block (even if it wasn’t used later in the body of the function).

In practice, do-while loops aren’t commonly used. Having the condition at the bottom of the loop obscures the loop condition, which can lead to errors. Many developers recommend avoiding do-while loops altogether as a result. We’ll take a softer stance and advocate for preferring while loops over do-while when given an equal choice.

Best practice

Favor while loops over do-while when given an equal choice.

7.9 -- For statements
7.7 -- Intro to loops and while statements

102 comments to 7.8 — Do while statements

  • Peter Baum

    At the top where the syntax is described, I think there should not be a semi-colon after the word "statement" because one form a statement can take is the compound statement using curly brackets and no following semicolon.  This is shown in the example.  (Some statements, of course, do end with a semicolon.)

  • Peter Baum

    Second sentence in the paragraph after the code-like defining syntax description; typo: "pathof"

  • Micah

    A couple quiz questions here would be nice, and maybe one or two more examples of how it's used practically. Not sure how much we can utilize it with what's been taught so far but it seems to have an underestimated amount of importance.

  • Afi

    hey plz tell me what is wrong with this code. How to use switch statements inside do-while loop?
    #include <iostream>
    using namespace std;

    int main()
        // selection must be declared outside do/while loop
        int selection;

            cout << "Please make a selection: \n";
            cout << "1) Addition\n";
            cout << "2) Subtraction\n";
            cout << "3) Multiplication\n";
            cout << "4) Division\n";
            cin >> selection;
        } while(selection) //(selection == 1|| selection == 2 || selection == 3 || selection == 4)
            switch (selection)
                case 1:
                    cout << "you want addition\n";
                case 2:
                    cout << "you want subtraction\n";
                case 3:
                    cout << "you want multiplication\n";
                case 4:
                    cout << "you want division\n";
                    cout << "you entered wrong operation\n";
        std::cout << "You selected option #" << selection << "\n";
        return 0;

    • Alex

      Where do you believe your code is behaving improperly? Looking at it, I don't necessarily see anything "wrong", but maybe I'm missing something.

      To use the switch inside the do-while, just move it inside the closing-brace of the switch.

  • justAnotherConfusedStudent

    I'm still confused as to what a do-while statement does. With the example code you have, will the do block run every time? So let's say I pick option 1 (addition), it just prints "You have selected option 1", and returns 0?

    And as for the alternative, if I pick an option that isn't any of the four listed, the function executes the while loop? What happens at the end of the while loop? Does the function return to the beginning of the while loop or the do block?

    • Alex

      The do block will run at least once. Then the while condition is evaluated. If the while condition evaluates to true, the loop will be executed again. This will continue until the while clause becomes false.

      So yes, if you pick 1, then the while clause will be false (because 1 != 1 is false, making the while condition false). If you pick anything other than 1 through 4, the while clause will be true, and the loop executes again from the top of the do block.

  • Alice

    Hi, i'm doing a congkak game and has problem when I choose the storehouse which contain no seed. I can't cin the input again. May i know what is the error?

  • Tath

    Hi, I copied the exact same code as shown in the lesson and tried to input a really large number into the program, but if that integer is >= 2147483648 (2^32 + 1), the program starts entering an infinite loop and I can't put in any more input. Any number <= 2147483647 seems fine. Negatives up to -2147483648 seem to be okay as well, but I don't know exactly how small it goes.

    I'm using code::blocks and my architecture uses (int) as a 4-byte integer (at least, typeof(int) returns 4). I suspect that overflow is the cause here, but I'm not exactly sure why.

    What is the cause of this?

    • Alex

      This has to do with the way std::cin handles invalid input. I talk more about why this happens and how to deal with it in lesson 5.10.

  • dezi

    i am asking with the do and while condition . if i want to ask the user for than one choose(to choose A and B not only one ), how should i write the code

  • dezi

    please how can i can i make the user to make more than one choice . like 2 or 3 choices

  • Jester

    Alex can you critic my code?

    • Alex

      Your code would be vastly improved by using if/else instead of just if, and also by using logical AND (&&) and logical OR (||) to combine multiple if statements.

  • Joshua Richards

    In the example above wouldn't it be:

    while (selection != 1 || selection != 2 || selection != 3 || selection != 4 )

    and if so why not? Cause this sounds like you have to choose all of them or it would relaunch the menu. Also, shouldn't there not be a semi-colon after the while expression?

    • Shiva

      || won't work in this case; it has to be &&.

      What Alex's loop does is run again as long as the user enters a choice other than 1,2,3 or 4. If the user enters any one of them, one of the four conditions will become false (e.g., enter 1, selection != 1 will become false). So the whole logical expression evaluates to false (as it is an AND), which breaks the loop and the control moves over to the rest of the program.

      The loop you gave will not work for the exact reason that you changed the &&'s into ||'s. Infact, it is an infinite loop! This loop terminates only if all the four conditions evaluates to false (since it is OR). This needs the selection to be equal to 1,2,3 AND 4 at the same time. How can this be possible? It might seem a little counter-intuitive at first, but it's pretty simple once you analyse the logic.

      The semi-colon after the while part is also required, since it is the end of the do-while statement (all statements in C++ ends with a semicolon). The normal while statement ends with the statement that forms the loop body, and not with the parenthesis. Thus the semicolon comes after the body-statement. The do-while loop is just a special construct in which the body-statement comes first and the condition last, so the semicolon comes after the condition expression.

      Hope that helps. :)

    • Alex

      AND vs OR is always challenging to get right when combined with NOT.

      The best way to do these things is to pick a sample number and see if it works like you expect. For example, what if we chose selection = 2?

      selection != 1 is true
      selection != 2 is false
      selection != 3 is true
      selection != 4 is true
      true || false || true || true is true, so we'd loop. But 2 is a valid selection, so clearly what you are suggesting is incorrect.

      Now do the same with AND instead of OR:
      true && false && true && true is false, so we wouldn't loop. That's what we want.

      We can do the same with an invalid choice, like 5, to make sure it handles invalid values as well.

  • Elpidius

    Using De Morgan's law touched upon in lesson 3.6 — Logical operators, the following is also the equivalent condition-expression in the do-while loop example:

  • Muhammad Aarif

    how to calculate how many item in the loop have been used?  for example in reservation hotel, 5 request have been made in the loop (the loop can be infinity) .3 for family room n 2 for single room, they all planned to stay for 5 night.How to make the output show all the total request for the room and the total night they stayed in the loop?

  • jim

    hey what is wrong in my program

    i have to arrange them in desending order??
    if you are having easy method plzzzzz help

  • jim

    i didn't understand why are you terminating the while with semicolon in the program you have given as an example??

  • bio

    i  did it at last ;)

    keep  it up with this amazing tutorial Alex,they are very helpfull!!!

  • bio

    i did split the funksion  in two

    but i'm still getting the same results:(

  • bio

    I tried to write a strucktured code for a simple calculator but i don't get the expected results

    • Alex

      Your function getInsertVariableControll() is trying to return two values. This is not allowed in C++. There are many ways to get around this, but the easiest is to simply split your function into two functions that each return one value.

  • Kevin

    I decided to take the code here and what I've learnt so far to make a calculator that takes two values, asks what operation, and throws up errors if an invalid character is entered. I have it functioning exactly how I want it... but I'm curious if I've made newbie mistakes, and if there are easier ways to do it.

  • R00kie

    Hi Alex,

    I was playing with a piece of code that I wrote testing the Do/While loops, a calculator pretty similar with the the ones in the comments above and I came across this problem :

    My calculator works pretty well, except when I try to enter an invalid number…it goes ballistic afterwards.

    How can I put a condition that checks the data type for my X and Y and if it’s not double/integer etc to simply cout a message like " you’ve entered an invalid character, not an integer/double etc " .

    What condition should I write for my "switch" or "if" to check if my data type is an integer/double , or "else" to show me and error message ???

    or better yet to show me the " Enter number " message again ???

    • Alex

      You can use the following code to detect a failed input and remove the invalid characters from the I/O stream:


    Shouldn't the and's (&&) in the above example be or's (||)?

    • codeez

      If we used Logical OR, we'd get 'short circuit evaluation' if the first || was true so we'd never even check to see if the next number was correct.

      Still learning, so correct me anyone if I'm wrong :)

  • Azmat Naseem

    thanx is very helpful

  • learningcpp

    Excellent tutorials, upto the point, 10pts++

  • Pixy

    Can you help me out with this code?

    What gets printed out? Would it be, 12 11 10 9 8 ??

  • brian Brake

    • Quinn

      Remember to keep your comments outside of the <pre> tags, because it makes reading what you're asking for difficult. :) As for your code, if you want to prompt the user to use the calculator again before exiting the program, you can put everything in a while loop. Take the below code as an example.

      • alwaysAstudent

      • Kushagra

        You can also use this code below
        #include <iostream>

        using namespace std;

        int main()
        double x;
        char op;
          double y;


                    std:: cout << " ENTER THE FIRST NUMBER :  "  <<std::endl;

            std::cin >> x;
            std::cout << "ENTER THE OPERATOR: " << std::endl;

            std::cin >> op;

            std::cout << " ENTER THE SECOND NUMBER: " <<std::endl;

            std::cin >>y;
                     if ((op !='+')&&(op != '-')&&(op!='*')&&(op!='/'))
                        std::cout << " \n ERROR! TRY AGAIN !! \n " <<std::endl;
                        if ((op =='+')||(op == '-')||(op=='*')||(op=='/'))
                            if (op=='+')
                                std::cout << x+y;
                            if (op == '-')
                                std::cout << x-y;
                            if (op== '*')
                                std::cout << x*y;
                            if (op == '/')
                                std::cout << x/y;

            while ((op !='+')&&(op != '-')&&(op!='*')&&(op!='/'));

            return 0;

    • ranchos

      the code you have written here will not run. after using the keyword (if) you must use (else if)!

      • lynx1241

        it's not a prerequisite to use else if. it's perfectly valid syntax. the difference is that when you use a variety of 'if statements' the program will run through each if statement. when using 'else if statements' the program will run through the statements until a statement is true, at that point it will skip all other 'else if statement'.

  • geoffrey mjuda banda

    This is a nice tutorial and beneficial to C++ learners. I would like to request for more tutorials to be sent to my email address. I hope i will benefit alot through this program.Keep it up.

    • I regret to inform you that I can not send tutorials directly to your email. However, you are welcome to read them on this website all you want.

  • daisy...

    is it possible to enter letters instead of numbers in do while loop statement?...
    can it be?...

  • Pathik

    One thing to note here is that the 'while' when using do with it works opposite to what the word exactly means in English.

    For example:

    This code is actually suppose to read x until(while) x is smaller y, but it actually reads x until x is bigger than y. You actually have to use 'while' as if it means 'if'.

    For example:

    • Your example is misleading because until and while actually have OPPOSITE meanings in english language. Consider: If you do something UNTIL X, you stop when X is true. If you do something WHILE X, you continue when X is true.

      Although C++ doesn't have an until keyword, it's not that hard to write the corresponding while statement. Simply write your statement as if it were an until statement, then replace until with while and flip the conditional using a logical not.

      For example, if we wanted to get user input until x < y:

      Convert to while and flip conditional:

      Now, assume y is 5, and the user enters x = 3. x < y is 3 < 5, which is true. !true is false, so this evaluates to while(false). That means the loop exits, which is what you wanted.

  • runner

    In the above code, when I input an integer other than 1,2,3,4, the menu reappears as expected. However, when I input an ASCII character, such as 'a', the program goes into an infinite loop. Why is that?

    • This is happening because cin >> nSelection is trying to read a number, and 'a' isn't a number. Consequently, the input into nSelection fails, the while loop conditional fails, and the loop repeats.

      There are several ways that we could go about fixing this problem.

      1) Read the input as a string (which can accept any type of input) and then convert the string into a number (we cover strings in chapter 6.6)
      2) Detect that the input call has failed and remove the invalid characters from cin. We cover how to do this in chapter 13, when we delve into C++ I/O.
      3) Restrict the user to entering only numeric data. Unfortunately, cin doesn't have kind of input character filtering functionality, which makes this rather hard to do in C++.

Leave a Comment

Put all code inside code tags: [code]your code here[/code]