The next example creates a simple four-function calculator to demonstrate do-while loops. Unlike for- and do-loops that perform the loop test at the loop's top, do-while loops evaluate the loop test at the loop's bottom. So, the program always executes the loop's body at least once. This behavior makes do-while loops a good choice where the loop test depends, at least in part, on a value calculated or input in the body. The example also nests a switch statement in the loop, causing two potentially confusing features. As you study the program, try to understand the case 'e' and the loop test: choice != 'e' && choice != 'E'.
#include <iostream> using namespace std; int main() { char choice; // choice must be defined outside the do-while double left; // left and right may be defined inside the do-while double right; do { // creates a new block with a new scope cout << "A\tAdd\n"; // prints a menu of options cout << "S\tSub\n"; cout << "M\tMult\n"; cout << "D\tDiv\n"; cout << "E\tExit\n"; cout << "\nChoice?: "; cin >> choice; // reads the user's choice cin.ignore(); // discards the new line - see the ignore function switch (choice) { case 'A': // either 'A' or 'a' selects addition case 'a': cout << "enter the first operand: "; cin >> left; cout << "enter the second operand: "; cin >> right; cout << left + right << endl; break; case 'S': // either 'S' or 's' selects subtraction case 's': cout << "enter the first operand: "; cin >> left; cout << "enter the second operand: "; cin >> right; break; case 'M': // either 'M' or 'm' selects multiplication case 'm': cout << "enter the first operand: "; cin >> left; cout << "enter the second operand: "; cin >> right; cout << left * right << endl; break; case 'D': // either 'D' or 'd' selects division case 'd': cout << "enter the first operand: "; cin >> left; cout << "enter the second operand: "; cin >> right; cout << left / right << endl; break; case 'E': // these cases don't do anything, but without case 'e': // them the program prints the default error message break; default : cout << "Unrecognized choice: " << // prints an error message if the user's input choice << endl; // doesn't match a valid choice break; } } // closes the do-while block and its scope while (choice != 'e' && choice != 'E'); // AND or OR? return 0; }
choice != 'E'
must be true. If the user enters 'E,' the result remains one true and one false value. The truth table for logical-OR (b) indicates that false OR true is true and true OR false is true. Either way, the test always evaluates to true, and the loop continues without end!char choice; double left; double right; double result; |
case 'A': case 'a': cout << "enter the first operand: "; cin >> left; cout << "enter the second operand: "; cin >> right; result = left + right; cout << result << endl; break; |
(a) | (b) |