< previous page page_464 next page >

Page 464
switch (grade)    // Wrong version
{
    case A :
    case B : cout << Good Work;
    case C : cout << Average Work;
    case D :
    case F : cout << Poor Work;
               numberInTrouble++;
    default : cout << grade <<  is not a legal letter grade.;
}
If grade happens to be H, control branches to the statement at the default label and the output is
H is not a legal letter grade.
Unfortunately, this case alternative is the only one that works correctly. If grade is A, the resulting output is this:
Good WorkAverage WorkPoor WorkA is not a legal letter grade.
Remember that after a branch is taken to a specific case label, control proceeds sequentially until either a break statement or the end of the Switch statement is encountered. Forgetting a break statement in a case alternative is a very common source of errors in C++ programs.
The Do-While Statement
The Do-While statement is a looping control structure in which the loop condition is tested at the end (bottom) of the loop. This format guarantees that the loop body is executed at least once. The syntax template for the Do-While is this:
DoWhileStatement
do
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
Statement
While (Expression);

As usual in C++, Statement is either a single statement or a block. Also, note that the Do-While ends with a semicolon.

 
< previous page page_464 next page >