AlgoViz

Switch Case

Easy

One value, many branches

Problem

A switch selects one branch based on the value of a single variable. Each case handles one value; break stops fall-through to the next case, and default handles anything unmatched.

In simple words

Pick one door to walk through based on a single value.

The idea

A switch compares a single value against a list of constant cases and jumps to the match. Unlike an if-chain it is a lookup rather than a sequence of tests, which makes it the clearer choice when you are dispatching on one discrete value like a menu option or an operator character.

The trick

  • Without `break`, execution falls through into the next case — occasionally useful, usually a bug.
  • `default` handles everything unmatched; include it so unexpected values are not silently ignored.
  • Cases must be compile-time constants, so a switch cannot test ranges or conditions.
Mon
Tue
Wed
Thu
Fri
Sat
Sun
Invalid
0
1
2
3
4
5
6
7
day2

Step 1 of 3. day = 2. A switch jumps straight to the matching label instead of testing each one. Values: Mon, Tue, Wed, Thu, Fri, Sat, Sun, Invalid. day 2.

1/3
Optimal
timespace
1switch (day) {2  case 1: print("Mon"); break;3  case 2: print("Tue"); break;4  ...5  default: print("Invalid");6}

Input

array
[Mon, Tue, Wed, Thu, Fri, Sat, Sun, Invalid]
day
2

Memory

day
2

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Examples

Example 1

Input:
day = 3
Output:
Wednesday
Explanation:
The switch jumps straight to case 3 rather than testing 1 and 2 first. The break stops it falling into Thursday.

Example 2

Input:
day = 9
Output:
Invalid day
Explanation:
No case matches, so default runs. A switch without a default silently does nothing here.

Finished the walkthrough? Add it to your streak.