5.6 — Do while statements

One interesting thing about the while loop is that if the loop condition is initially false, the while loop will not execute at all. It is sometimes the case that we know we want a loop to execute at least once, such as when displaying a menu. To help facilitate this, C++ offers the do-while loop:

while (condition);

The statement in a do-while loop always executes at least once. After the statement has been executed, the do-while loop checks the condition. If the condition is true, the CPU jumps back to the top of the do-while loop and executes it again.

Here is an example of using a do-while loop to display a menu to the user and wait for the user to make a valid choice:

One interesting thing about the above example is that the selection variable must be declared outside of the do block. Why do you think that is?

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 while conditional is executed. But we need the variable to use in the while conditional -- consequently, the selection variable must be declared outside the do block.

Generally it is good form to use a do-while loop instead of a while loop when you intentionally want the loop to execute at least once, as it makes this assumption explicit -- however, it’s not that big of a deal either way.

5.7 -- For statements
5.5 -- While statements

45 comments to 5.6 — Do while statements

  • 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++.

  • 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.

  • daisy...

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

  • 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.

  • 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

    • 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’.

  • Pixy

    Can you help me out with this code?

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

  • learningcpp

    Excellent tutorials, upto the point, 10pts++

  • Azmat Naseem

    thanx dear…it is very helpful


    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 🙂

  • 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:

  • 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.

  • 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.

  • bio

    i did split the funksion  in two

    but i’m still getting the same results:(

  • bio

    i  did it at last 😉

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

  • jim

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

  • jim

    hey what is wrong in my program

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

  • 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?

  • 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:

  • 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.

  • 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.

  • dezi

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

  • 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

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter




4 × 3 =