do stmt body of the loop while (expression)
---------------------------- // input a negative number from user do { cout < "Enter negative number: "; cin >> num; } while (num >= 0); User given no indication if input is "wrong". see below for improved version of thisConventional to use braces around body even if only one statement to avoid confusing the while for the while statement.
// input valid grade from user do { cin >> gr; } while (gr!='A' && gr!='B' && gr!='C' && gr !='D' && gr!='F'); ---------------------------- // input valid grade. Error message to user do { cin >> gr; if (gr!='A' && gr!='B' && gr!='C' && gr !='D' && gr!='F') cout << "ERROR. Must be ABCDF. Re-enter: "; } while (gr!='A' && gr!='B' && gr!='C' && gr !='D' && gr!='F'); ---------------------------- // input value in range 1 thru 5 do { cin >> choice; if (choice<1 || choice>5) cout << "ERROR. Invalid choice: " << choice << " Must be 1 thru 5. Re-enter: "; } while (choice<1 || choice>5); ---------------------------- bool error; // input a negative number from user do { cout << "Enter negative number: "; cin >> num; if (error = num>=0) // assign result of >= (true or false) cout << "ERROR. Must be negative number." << endl; } while (error); //will be true or false from the assignmentSomeone did a study once and found that loops were 70% while and 30% do.
The GPA program revisited using do and switch. gpa2.cpp
Next (built-in functions)