An Example of the Coding the Case Selection Structure


If you are not familiar with the basic concepts involved in using the Case Selection structure, you may find it helpful to review the web page entitled Selection Using the Case Selection Structure before reading the following text. If you are unfamiliar with the basic concept of selection structure in general, you should review the web page entitled Selection Using the if Statement in a C++ Program.

Case Selection can be used to document selective situations where multiple processing paths are required as the result of the value of a single variable. This approach has restrictions. Case Selection can be used only in situations where the branching is based entirely on the value of a single variable and where those values are part of a set of ordinal data.

The Case Selection structure clearly conveys the nature of any selective process that involves the selection of one path as the result of examining the value of a single variable. It does not imply any order of testing. It merely shows that a specific value of a single variable will cause a particular processing path to be taken.


Algorithm (Flowchart Segment) - Case Selection

In the example below, five possible paths might be followed depending on the value stored in the character storage location X. Each path (leg) is selected based on the individual value(s) that might be stored in X.

case example illustration


C++ Source Code - Case Selection

  switch (X)
  {
    case 'A': A=1; break;
    case 'B': A=2; Y=1; break;
    case 'C': A=3; break;
    case 'D':
    case 'E': A=4; break;
    default: A=0; break;
  }

Notice:

The use of indentation and the positions of the carriage returns in the code are irrelevant.

PATH: Instructional Server> COP 2000> Examples>