Switch statement accepts expression (like variable or constant) and executes one of many code blocks.
case
specifies the value to check.
break
separates code blocks.
default
is used to handle cases when expression's value
doesn't match any of the cases. It's not mandatory to specify
Let's look at a program that converts number into traffic light color.
Rules are the following:
Output:
Since the value of number
is 2
, the code at
lines 16
executes.
Let's analyze a program that depending on angles count prints shape name.
Rules are the following:
Output:
Since anglesCount
is neither of the cases value (3, 4, 5)
the code at line 22
executes.
A code block inside case can be executed for one or more values.
Let's have a program that rates performance depending on it's score.
Rules are the following:
Output:
performance
value is matched by case 8
and thus line 27
executes.