Here is a snippet from an example on C++.com.
They use what looks like a do loop.
I tried putting it into their search, but nothing came back for "do".

As far as I can tell it forces the loop intially, otherwise the while statement would cause it drop through without it.

What is this the "do" statement intended for and when is it appropriate?

The fact is, I wrote a similar program without "do" . I just intialized the variable to 1.

code from C++:

// vector::push_back
#include <iostream>
#include <vector>
using namespace std;

int main ()
{
  vector<int> myvector;
  int myint;

  cout << "Please enter some integers (enter 0 to end):\n";

  do {
    cin >> myint;
    myvector.push_back (myint);
  } while (myint);

  cout << "myvector stores " << (int) myvector.size() << " numbers.\n";

  return 0;
}

Now, here is the way I did it without "do".

#include <iostream>
#include <vector>
using namespace std;

vector<int> vint;
int input;

int main()
{
        cout << "Enter an integer (Enter 0 to exit) ";
        while(input)
        {
        cin >> input;
        vint.push_back(input);
        }

        vector<int>::iterator it;

for(it=vint.begin(); it < vint.end(); it++)
{
cout << *it << " ";
}
cout << endl;
return 0;
}

Recommended Answers

All 3 Replies

Its not a 'do' statement. Its called a 'do..while' loop, much like the 'while' loop except that the enclosing block is guaranteed to run at least once.

int i = 0;
while(i)
{
   //some code, this would never be executed
   // since the condition is checked before entering the block
}

do
{
    //this code will be executed at least once.
} while(i);

Its just a convenience thingy. Most people find some solutions more expressive using the do..while loop. For example, since I know that my application menu should be displayed at least once irrespective of the user input, I would use a 'do...while' loop. That being said, all 'while' loops can be converted to 'do...while' loops by losing / gaining some expressiveness.

Member Avatar for iamthwee

>What is this the "do" statement intended for and when is it appropriate?

A do...While loop, is like borrowing your Dad's car them telling him later.

A While loop, is like asking your dad before you borrow the car.

The first premise has the advantage that it happens at least once even if your dad says no.

The second nothing is gonna happen if your dad says 'no'.

It all depends on the situation in your program.

Thanks guys.

This all goes to prove even more that math and programming are not "spectator sports". "Ya gotta do it to glue it".

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.