Illustration of switch statement:
Here are the two illustrations of calling this function:
>> quiz = 22;
>> lg = switchletgrade(quiz)
>> quiz = 9;
Note that it is supposed that the user will enter an integer value. When the user does not, either an error message will be printed or a wrong result will be returned. As the similar action of printing 'A' is desired for more than one situation, these can be combined as shown below:
grade = 'A';
grade = 'B';
(The curly braces around the case expressions 10 & 9 are essential.)
In this illustration, we checked the error first using an if-else statement, and then if the grade was in the valid range, used the switch statement to find the corresponding letter grade.
At times the otherwise clause is used rather than for the error message. For illustration, if the user is assumed to enter only a 1, 3, or 5, the script may be organized as shown below:
In this situation, actions are taken if the user properly enters one of the valid options. When the user does not, the otherwise clause handles, by printing an error message.
Note that the use of two single quotes within the string to print one.
Enter a 1, 3, or 5: 4