2. Conditional Statements

2.3. Switch Statement

          If there are multiple actions for multiple conditions, the code can be written with many layers of ifelse-if. But a more elegant solution to this is the use of switch. The code below is a sample block on how to use switch.


          Switch works by evaluating the expression stated and compares the value to each of the cases specified. You can specify as many cases as you want. If the value does not match any of the cases, the code block specified under default will be executed. 

          Notice that there are break statements after every case. This is so that the execution of the next cases will be skipped. This is important because when the expression is true for case A, it can also be true for case B. Look at the code below for an example:


          The code above gives an equivalent alphabetic rating for a given numerical rating. A grade of less that 70 would merit a rating of “D.” A grade of less than 60 would merit an “E.” Let’s say that you are evaluating the rating of a grade of 59. It is less than 60 and less than 70. When there is no break in between case statements, it can be evaluated as true for both cases and the final alphabetical rating of the expression would be from whichever case was declared last in the code.