6.8 switch Multiple-Selection Statement

We discussed the if and ifelse selection statements in Chapter 5. C# provides the switch multiple-selection statement to perform different actions based on the possible values of an expression, known as the switch expression. Each action is associated with one or more of the switch expression’s possible values. These are specified as constant integral expressions or a constant string expressions:

  • A constant integral expression is any expression involving character and integer constants that evaluates to an integer value—i.e., values of type sbyte, byte, short, ushort, int, uint, long, ulong and char, or a constant from an enum type (enum is discussed in Section 7.9).

  • A constant string expression is any expression composed of string literals or const string variables that always results in the same string.

6.8.1 Using a switch Statement to Count A, B, C, D and F Grades

Figure 6.9 calculates the class average of a set of numeric grades entered by the user, and uses a switch statement to determine whether each grade is the equivalent of an A, B, C, D or F and to increment the appropriate grade counter. The program also displays a summary of the number of students who received each grade.

Fig. 6.9 Using a switch statement to count letter grades.

Alternate View

  1    // Fig. 6.9: LetterGrades.cs
  2    // Using a switch statement to count letter grades.
  3    using System;
  4
  5    class LetterGrades
  6    {
  7       static void Main()
  8       {
  9          int total = 0; // sum of  grades
 10          int gradeCounter = 0; //  number of grades entered
 11          int aCount = 0; // count  of A grades
 12          int bCount = 0; // count  of B grades
 13          int cCount = 0; // count  of C grades
 14          int dCount = 0; // count  of D grades
 15          int fCount = 0; // count  of F grades
 16
 17          Console.WriteLine("Enter the integer grades in the range 0-100.");
 18          Console.WriteLine(
 19             "Type <Ctrl> z and press Enter to terminate input:");
 20
 21          string input = Console.ReadLine(); // read user input
 22
 23          // loop until user enters the end-of-file indicator (<Ctrl> z)
 24          while (input != null)
 25          {
 26             int grade = int.Parse(input); // read grade off user input
 27             total += grade; // add grade to total
 28             ++gradeCounter; // increment number of grades
 29
 30             // determine which grade was entered     
 31             switch (grade / 10)                      
 32             {                                        
 33                case 9: // grade was in the 90s       
 34                case 10: // grade was 100             
 35                   ++aCount; // increment aCount      
 36                   break; // necessary to exit switch 
 37                case 8: // grade was between 80 and 89
 38                   ++bCount; // increment bCount      
 39                   break; // exit switch              
 40                case 7: // grade was between 70 and 79
 41                   ++cCount; // increment cCount      
 42                   break; // exit switch              
 43                case 6: // grade was between 60 and 69
 44                   ++dCount; // increment dCount      
 45                   break; // exit switch              
 46                default: // grade was less than 60    
 47                   ++fCount; // increment fCount      
 48                   break; // exit switch              
 49             }                                        
 50
 51             input = Console.ReadLine(); // read user input
 52          }
 53
 54          Console.WriteLine("
Grade Report:");
 55
 56          // if user entered at least one grade...
 57          if (gradeCounter != 0)
 58          {
 59             // calculate average of all grades entered
 60             double average = (double) total / gradeCounter;
 61
 62             // output summary of results
 63             Console.WriteLine(
 64                $"Total of the {gradeCounter} grades entered is {total}");
 65             Console.WriteLine($"Class average is {average:F}");
 66             Console.WriteLine("Number of students who received each grade:");
 67             Console.WriteLine($"A: {aCount}"); // display number of A grades
 68             Console.WriteLine($"B: {bCount}"); // display number of B grades
 69             Console.WriteLine($"C: {cCount}"); // display number of C grades
 70             Console.WriteLine($"D: {dCount}"); // display number of D grades
 71             Console.WriteLine($"F: {fCount}"); // display number of F grades
 72           }
 73           else // no grades were entered, so output appropriate message
 74           {
 75              Console.WriteLine("No grades were entered");
 76           }
 77       }
 78    }

Enter the integer grades in the range 0-100.
Type <Ctrl> z and press Enter to terminate input:
99
92
45
57
63
71
76
85
90
100
^Z

Grade Report:
Total of the 10 grades entered is 778
Class average is 77.80
Number of students who received each grade:
A: 4
B: 1
C: 2
D: 1
F: 2r

Lines 9 and 10 declare and initialize to 0 local variables total and gradeCounter to keep track of the sum of the grades entered by the user and the number of grades entered, respectively. Lines 11–15 declare and initialize to 0 counter variables for each grade category. The Main method has two key parts. Lines 21–52 read an arbitrary number of integer grades from the user using sentinel-controlled iteration, update variables total and gradeCounter, and increment an appropriate letter-grade counter for each grade entered. Lines 54–76 output a report containing the total of all grades entered, the average grade and the number of students who received each letter grade.

Reading Grades from the User

Lines 17–19 prompt the user to enter integer grades and to type Ctrl + z, then press Enter to terminate the input. The notation Ctrl + z means to hold down the Ctrl key and tap the z key when typing in a Command Prompt. Ctrl + z is the Windows key sequence for typing the end-of-file indicator. This is one way to inform an app that there’s no more data to input. If Ctrl + z is entered while the app is awaiting input with a ReadLine method, null is returned. (The end-of-file indicator is a system-dependent keystroke combination. On many non-Windows systems, end-of-file is entered by typing Ctrl + d.) In Chapter 17, Files and Streams, we’ll see how the end-of-file indicator is used when an app reads its input from a file. Windows typically displays the characters ^Z in a Command Prompt when the end-of-file indicator is typed, as shown in the program’s output.

Line 21 uses Console’s ReadLine method to get the first line that the user entered and store it in variable input. The while statement (lines 24–52) processes this user input. The condition at line 24 checks whether the value of input is nullConsole’s ReadLine method returns null only if the user typed an end-of-file indicator. As long as the end-of-file indicator has not been typed, input will not be null and the condition will pass.

Line 26 converts the string in input to an int type. Line 27 adds grade to total. Line 28 increments gradeCounter.

Processing the Grades

The switch statement (lines 31–49) determines which counter to increment. In this example, we assume that the user enters a valid grade in the range 0–100. A grade in the range 90–100 represents A, 80–89 represents B, 70–79 represents C, 60–69 represents D and 0–59 represents F. The switch statement consists of a block that contains a sequence of case labels and an optional default label. These are used in this example to determine which counter to increment based on the grade.

The switch Statement

When control reaches the switch statement, the app evaluates the expression grade / 10 in the parentheses—this is the switch expression. The app attempts to match the value of the switch expression with one of the case labels. The switch expression in line 31 performs integer division, which truncates the fractional part of the result. Thus, when we divide any value in the range 0–100 by 10, the result is always a value from 0 to 10. We use several of these values in our case labels. For example, if the user enters the integer 85, the switch expression evaluates to int value 8. If a match occurs between the switch expression and a case (case 8: at line 37), the app executes the statements for that case. For the integer 8, line 38 increments bCount, because a grade in the 80s is a B.

The break statement (line 39) causes program control to proceed with the first statement after the switch (line 51), which reads the next line entered by the user and assigns it to the variable input. Line 52 marks the end of the body of the while statement that inputs grades, so control flows to the while’s condition (line 24) to determine whether the loop should continue executing based on the value just assigned to the variable input.

Consecutive case Labels

The switch’s cases explicitly test for the values 10, 9, 8, 7 and 6. Lines 33–34 test for the values 9 and 10 (both of which represent the grade A). Listing case labels consecutively in this manner with no statements between them enables the cases to perform the same set of statements—when the switch expression evaluates to 9 or 10, the statements in lines 35–36 execute. The switch statement does not provide a mechanism for testing ranges of values, so every value to be tested must be listed in a separate case label. Each case can have multiple statements. The switch statement differs from other control statements in that it does not require braces around multiple statements in each case.

The default Case

If no match occurs between the switch expression’s value and a case label, the statements after the default label (lines 47–48) execute. We use the default label in this example to process all switch-expression values that are less than 6 —that is, all failing grades. If no match occurs and the switch does not contain a default label, program control simply continues with the first statement (if there’s one) after the switch statement.

Good Programming Practice 6.1

Although each case and the default label in a switch can occur in any order, place the

No “Fall Through” in the C# switch Statement

In many other programming languages containing switch, the break statement is not required at the end of a case. In those languages, without break statements, each time a match occurs in the switch, the statements for that case and subsequent cases execute until a break statement or the end of the switch is encountered. This is often referred to as “falling through” to the statements in subsequent cases. This leads to logic errors when you forget the break statement. C# is different from other programming languages—after the statements in a case, you’re required to include a statement that terminates the case, such as a break, a return or a throw;1 otherwise, a compilation error occurs.2

Displaying the Grade Report

Lines 54–76 output a report based on the grades entered (as shown in the input/output window in Fig. 6.9). Line 57 determines whether the user entered at least one grade—this helps us avoid dividing by zero. If so, line 60 calculates the average of the grades. Lines 63–71 then output the total of all the grades, the class average and the number of students who received each letter grade. If no grades were entered, line 75 outputs an appropriate message. The output in Fig. 6.9 shows a sample grade report based on 10 grades.

6.8.2 switch Statement UML Activity Diagram

Figure 6.10 shows the UML activity diagram for the general switch statement. Every set of statements after a case label normally ends its execution with a break or return statement to terminate the switch statement after processing the case. Typically, you’ll use break statements. Figure 6.10 emphasizes this by including break statements in the activity diagram. The diagram makes it clear that the break statement at the end of a case causes control to exit the switch statement immediately.

Fig. 6.10 switch multiple-selection statement UML activity diagram with break statements.

6.8.3 Notes on the Expression in Each case of a switch

In the switch statements cases, constant integral expressions can be character constants— specific characters in single quotes, such as 'A', '7' or '$' —which represent the integer values of characters. (Appendix C shows the integer values of the characters in the ASCII character set, which is a popular subset of the Unicode character set used by C#.) A string constant (or string literal) is a sequence of characters in double quotes, such as "Welcome to C# Programming!" or a const string variable. For string s, you also can use null or string.Empty.

The expression in each case also can be a constant—a value which does not change for the entire app. Constants are declared with the keyword const (discussed in Chapter 7). C# also has a feature called enumerations, which we also present in Chapter 7. Enumeration constants also can be used in case labels. In Chapter 12, we present a more elegant way to implement switch logic—we use a technique called polymorphism to create apps that are often clearer, easier to maintain and easier to extend than apps using switch logic.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset