Switch Statement

Switch statement accepts expression (like variable or constant) and executes one of many code blocks.

Syntax

case specifies the value to check.

break separates code blocks.

defaultis used to handle cases when expression's value doesn't match any of the cases. It's not mandatory to specify

Basic Example

Let's look at a program that converts number into traffic light color.

Rules are the following:

  • 1 - red
  • 2 - yellow
  • 3 - green

Output:

Since the value of number is 2, the code at lines 10 executes.

Default Example

Let's analyze a program that depending on angles count prints shape name.

Rules are the following:

  • 3 - Triangle
  • 4 - Quadrilateral
  • 5 - Pentagon
  • Any other value is considered invalid

Output:

Since anglesCount is neither of the cases value (3, 4, 5) the code at line 16 executes.

Multiple Values Case

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:

  • 0 to 3 - low
  • 4 to 7 - medium
  • 8 to 10 - high

Output:

performance value is matched by case 8 and thus line 21 executes.