// CS 1621 Fall 2005 // Examples of conditional loops in C++ -- using pretest and posttest // loops to emulate the other. #include using namespace std; int main() { int value; bool done = false; // Classic example where a posttest loop applies -- error checking // user input do { cout << "Enter a positive integer: " << endl; cin >> value; if (value > 0) done = true; } while (!done); cout << "Thanks for your input of " << value << endl; // Pretest loop to simulate posttest loop. Note that we "rig" the // condition initially so that it will definitely be true. Once the // first iteration has occurred, the condition can be true or false. // This example could also be done without the bool variable. done = false; while (!done) { cout << "Enter a positive integer: " << endl; cin >> value; if (value > 0) done = true; } cout << "Thanks for your input of " << value << endl; // Classic example of a pretest loop -- user enters a sequence of data, // any of which (including the first) could be a sentinel value, // terminating the loop. cout << "Please enter a sequence of positive integers (<= 0 to quit)" << endl; cin >> value; while (value > 0) { cout << "The current value is " << value << endl; cout << "Please enter the next value (<= 0 to quit)" << endl; cin >> value; } cout << "Your sequence is finished" << endl; // Posttest loop to simulate pretest loop. Now we have to test the // condition before entering the loop, using an if statement. This // allows for the possibility of 0 iterations. cout << "Please enter a sequence of positive integers (<= 0 to quit)" << endl; cin >> value; if (value > 0) { do { cout << "The current value is " << value << endl; cout << "Please enter the next value (<= 0 to quit)" << endl; cin >> value; } while (value > 0); } cout << "Your sequence is finished" << endl; }