Multiple Selection

Page last updated 04/21/99

The need for multiple selection

The if( ) structure, as presented so far, allows for a one-way decision (the if-then or guard) or a two-way decision (the if-then-else or alternative).  There are times that we need to make a choice from several options.

The pattern in C++ is An example is...
if(cond-1){

   action-1

   ...

} else if(cond-2){

   action-2

   ...

} else if (cond-3){

   action-3

   ...

} ...

   ...

} else if (cond-n-1){

   action-n-1

   ...

} else {

   action-n

   ...

}
if(score>=90){

    grade = "A";

} else if(score>=80){

    grade = "B";

} else if(score>=70){

    grade = "C";

} else if(score>=60){

    grade = "D";

} else {

    grade = "F";

}

 

 

Notes on the multiple selection

Use the { } whether or not there is just one statement in the action.

Line the braces up vertically.

Indent the actions from the if statement line.

Always have an else part for a "catch-all".

You don't have to test for the opposite of something you tested earlier.

...

} else if(score>=80 && score<90){//the red part is unnecessary

The similar example on page 271 is wrong.  Without the else's, as they have it, the greyed components are necessary. Why?

The example on 273 works only because of the multiple returns as the actions.

 

 

Testing Multiple Selections

When designing selection structures you need to test each path through the structure.   This means testing and causing each of the actions to be executed. As a general rule you should cause each part of the condition to be true and to be false.  As the complexity of the code increases the number of test cases must increase at least linearly with the number of conditions. Sometimes even more so.

The other areas of testing is to check the bounds or the extremes of the program.   If the program is built for a range of numbers between 0 and 100, test what happens with 0, 100, something in between, with -1 and with 101.  The in between cases then ought to be tesing the various actions within the normal selection options.

Testing inequalities ought to include what happens when equal.  See the self check on page 275.