Navigation



5.6 — Do while statements

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

do
    statement;
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:

#include <iostream>

int main()
{
    using namespace std;

    // nSelection must be declared outside do/while loop
    int nSelection;

    do
    {
        cout << "Please make a selection: " << endl;
        cout << "1) Addition" << endl;
        cout << "2) Subtraction" << endl;
        cout << "3) Multiplication" << endl;
        cout << "4) Division" << endl;
        cin >> nSelection;
    } while (nSelection != 1 && nSelection != 2 &&
            nSelection != 3 && nSelection != 4);

    // do something with nSelection here
    // such as a switch statement

    return 0;
}

One interesting thing about the above example is that the nSelection variable must be declared outside of the do block. Think about it for a moment and see if you can figure out why that is.

If the nSelection variable is declared inside the do block, it will 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 nSelection 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
Index
5.5 — While statements

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

    do
    {
    	cin >> x;
    }while (x < y);
    

    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:

    do
    {
    	cin >> x;
    }while/*(if)*/ (x < y);
    
    • 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:

      do
      {
          cin >> x;
      } until (x < y); // C++ doesn't understand until
      

      Convert to while and flip conditional:

      do
      {
          cin >> x;
      } while (!(x < y));
      

      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.

  • brian Brake
    Newbie here.  Is there a more efficient way to code (see below). Also, if I wanted to prompt the user to use the calculator again, would i have to nest a bool within each IF?  Thanks for your help :)
    
    #include <iostream>
    using namespace std;
     int main()
    {
        int nSelection;
        double var1, var2;
    
        do
        {
            cout << "Please make a selection: " << endl;
            cout << "1) Addition" << endl;
            cout << "2) Subtraction" << endl;
            cout << "3) Multiplication" << endl;
            cout << "4) Division" << endl;
            cin >> nSelection;
        }
    
        while (nSelection != 1 && nSelection != 2 &&
                nSelection != 3 && nSelection != 4);
    
          if (nSelection == 1)
              {
              cout << "Please enter the first whole number ";
              cin >> var1;
              cout << "Please enter the second whole number ";
              cin >> var2;
             cout << "The result is " << (var1+var2) << endl;
             }
          if (nSelection == 2)
            {
              cout << "Please enter the first whole number ";
              cin >> var1;
              cout << "Please enter the second whole number ";
              cin >> var2;
             cout << "The result is " << (var1-var2) << endl;
             }
          if (nSelection == 3)
              {
              cout << "Please enter the first whole number ";
              cin >> var1;
              cout << "Please enter the second whole number ";
              cin >> var2;
             cout << "The result is " << (var1*var2) << endl;
             }
            if (nSelection == 4)
              {
              cout << "Please enter the first whole number ";
              cin >> var1;
              cout << "Please enter the second whole number ";
              cin >> var2;
             cout << "The result is " << (var1/var2) << endl;
              }
    
        return 0;
    }
    
    • 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.

      #include <iostream>
      using namespace std;
       int main()
      {
          int nSelection;
          double var1, var2;
          while (1)
          {
              do
              {
                  cout << "Please make a selection: " << endl;
                  cout << "1) Addition" << endl;
                  cout << "2) Subtraction" << endl;
                  cout << "3) Multiplication" << endl;
                  cout << "4) Division" << endl;
                  cout << "5) Exit" << endl;
                  cin >> nSelection;
              } while (nSelection != 1 && nSelection != 2 &&
                       nSelection != 3 && nSelection != 4 &&
                       nSelection != 5);
      
              if (nSelection == 1)
              {
                  cout << "Please enter the first whole number ";
                  cin >> var1;
                  cout << "Please enter the second whole number ";
                  cin >> var2;
                  cout << "The result is " << (var1+var2) << endl;
              }
              else if (nSelection == 2)
              {
                  cout << "Please enter the first whole number ";
                  cin >> var1;
                  cout << "Please enter the second whole number ";
                  cin >> var2;
                  cout << "The result is " << (var1-var2) << endl;
              }
              else if (nSelection == 3)
              {
                  cout << "Please enter the first whole number ";
                  cin >> var1;
                  cout << "Please enter the second whole number ";
                  cin >> var2;
                  cout << "The result is " << (var1*var2) << endl;
              }
              else if (nSelection == 4)
              {
                  cout << "Please enter the first whole number ";
                  cin >> var1;
                  cout << "Please enter the second whole number ";
                  cin >> var2;
                  cout << "The result is " << (var1/var2) << endl;
              }
              else
              {
                  return 0;
              }
          }
      }
      • alwaysAstudent

        #include
        using namespace std;
        int main()
        {
        int nSelection;
        double var1, var2;

        do
        {
        // Avoid redundancy of code.

        cout <> var1;
        cout <> var2;

        cout << "\n Please make a selection: ” << endl;
        cout << "1) Addition" << endl;
        cout << "2) Subtraction" << endl;
        cout << "3) Multiplication" << endl;
        cout << "4) Division" << endl;
        cout << "5) Exit" <> nSelection;

        // Use the beautiful tool, switch-case, built precisely for the purpose !

        switch (nSelection)
        {

        case 1 :
        cout << "\n The result is " << (var1+var2) << endl;
        break;

        case 2 :
        cout << "\n The result is " << (var1-var2) << endl;
        break;

        case 3 :
        cout << "\n The result is " << (var1*var2) << endl;
        break;

        case 4 :
        cout << "\n The result is " << (var1/var2) << endl;
        break;

        case 5 :
        cout<<"\n See you later !";
        return 0;

        default :
        cout << "\n Your selection was invalid ! Please choose again ! ";
        break;

        } // End of Switch-Case

        }while (nSelection != 5); // Putting an Exit option saves a lot of concerns regarding exit.

        }

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

    • alwaysAstudent

      #include
      using namespace std;
      int main()
      {
      int nSelection;
      double var1, var2;

      // Avoid redundancy of code. Put common parts of code together.

      cout <> var1;
      cout <> var2;

      do
      {
      cout << "\n Please make a selection: ” << endl;
      cout << "1) Addition" << endl;
      cout << "2) Subtraction" << endl;
      cout << "3) Multiplication" << endl;
      cout << "4) Division" << endl;
      cout << "5) Exit" <> nSelection;

      // Use the beautiful tool, switch-case, built precisely for the purpose !

      switch (nSelection)
      {

      case 1 :
      cout << "\n The result is " << (var1+var2) << endl;
      break;

      case 2 :
      cout << "\n The result is " << (var1-var2) << endl;
      break;

      case 3 :
      cout << "\n The result is " << (var1*var2) << endl;
      break;

      case 4 :
      cout << "\n The result is " << (var1/var2) << endl;
      break;

      case 5 :
      cout<<"\n See you later !";
      return 0;

      default :
      cout << "\n Your selection was invalid ! Please choose again ! ";
      break;

      } // End of Switch-Case

      }while (nSelection != 5); // Putting an Exit option saves a lot of concerns regarding exit.

      }

      /* I hope this helps. Pls do let me know what you all think. */

  • Pixy

    Can you help me out with this code?

     int x =12;
    do
    {
      printf("%dn", x);
    x--;
    } while (x<7); 

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

  • learningcpp

    Excellent tutorials, upto the point, 10pts++

  • hi sir can u plss help me plss post some c++ program like but 200lines help me plss

  • Azmat Naseem

    thanx dear…it is very helpful

  • Bao Nguyen

    Is there anyone know what is this ” cout var1 ” above?
    Please explain or where can I find this sign “” info on this tutorial?

    Thanks

  • Bao Nguyen

    The sign does not show up :

  • EXPLOSIVEXPLOSION

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

  • zee

    hi friends i am new comer in c++ i am so confused about do while loop some1 plz help me

You must be logged in to post a comment.