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'.
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)
A calc.cpp variation. The first version of calc.cpp evaluates the selected arithmetic expression in the output statement. This behavior solves the problem of creating a simple calculator but doesn't allow us to extend it by reusing a calculated value as one of the operands. The second version saves the calculated value in a new variable, the first step for implementing the proposed extension.
The program defines a new variable in function-scope. The program could also define the variable in the do-while loop but not in the switch.
The program now saves the operation's result in the new variable, where the program can use it in subsequent operations.