Switch / Match Statement
Switch / Match Statement
Learn how switch and match statements help programs choose one action from many possible options in a clean and organized way.
What is a Switch / Match Statement?
A Switch / Match statement is a decision-making structure used when a program needs to choose one block of code from many possible options.
In simple words, a switch or match statement checks the value of an expression and compares it with multiple possible cases. When a matching case is found, the related block of code is executed.
It is especially useful when a program has many fixed choices, such as menu options, days of the week, calculator operations, user roles, status codes, or command choices.
Easy Real-Life Example
Switch Statement as an Elevator Button
Imagine an elevator panel. If you press button 1, the elevator goes to floor 1. If you press button 2, it goes to floor 2. If you press button 3, it goes to floor 3.
Similarly, a switch statement checks the selected value and runs the matching action.
SWITCH floorNumber
CASE 1:
DISPLAY "Going to Floor 1"
CASE 2:
DISPLAY "Going to Floor 2"
CASE 3:
DISPLAY "Going to Floor 3"
DEFAULT:
DISPLAY "Invalid floor"
END SWITCH
Why is Switch / Match Statement Needed?
When a program has many possible choices, writing many IF ELSE IF conditions can become long and difficult to read. A switch or match statement makes such logic cleaner and more organized.
Importance of Switch / Match Statement
- It helps choose one action from many options.
- It improves readability for menu-based decisions.
- It avoids long and repetitive else-if ladders.
- It is useful when comparing the same value against multiple cases.
- It makes fixed-choice decision logic easier to understand.
- It works well for calculator operations, menu choices, days, months, roles, and status values.
- It helps organize branching logic in a structured way.
- It supports cleaner program flow for multiple alternatives.
General Syntax of Switch Statement
The language-neutral structure of a switch statement is:
SWITCH expression
CASE value1:
statements for value1
CASE value2:
statements for value2
CASE value3:
statements for value3
DEFAULT:
statements when no case matches
END SWITCH
The expression is checked once. Its value is compared with each case. If a case matches, the statements for that case are executed.
General Syntax of Match Statement
A match statement is similar to a switch statement, but in some modern programming languages it may support more flexible matching, such as matching values, patterns, types, or structures.
MATCH expression
CASE pattern1:
statements for pattern1
CASE pattern2:
statements for pattern2
CASE pattern3:
statements for pattern3
DEFAULT:
statements when no pattern matches
END MATCH
For this language-neutral course, students can understand SWITCH and MATCH as decision structures used to choose one matching case from many possible choices.
How Switch / Match Statement Works
A switch or match statement follows a clear decision flow.
Working Steps
- The program evaluates the expression or value.
- The value is compared with the first case.
- If it matches, the related block executes.
- If it does not match, the next case is checked.
- This continues until a matching case is found.
- If no case matches, the default block executes if it exists.
- After the matching block finishes, the program continues after the switch or match structure.
Switch / Match Statement Flow
START
↓
Evaluate expression
↓
Does it match Case 1?
├── Yes → Execute Case 1
└── No → Check Case 2
├── Yes → Execute Case 2
└── No → Check Case 3
├── Yes → Execute Case 3
└── No → Execute Default
↓
Continue program
This flow shows how the program checks cases one by one until a matching option is found.
Main Parts of a Switch / Match Statement
| Part | Meaning | Example |
|---|---|---|
| Expression | The value being checked. | choice, operation, dayNumber |
| Case | A possible value or pattern to match. | CASE 1, CASE "admin" |
| Case Block | The statements that run when a case matches. | DISPLAY "Monday" |
| Default | The fallback block when no case matches. | DISPLAY "Invalid choice" |
| Break / Exit | Stops execution of the matched case in languages that require it. | BREAK |
Example 1: Calculator Operation
A calculator is a perfect example of using a switch or match statement because the operation is selected from fixed choices.
/*
This program selects calculator operation using SWITCH.
*/
ENTRY POINT
DECLARE firstNumber AS DECIMAL = 0.0
DECLARE secondNumber AS DECIMAL = 0.0
DECLARE operation AS TEXT = ""
DECLARE result AS DECIMAL = 0.0
DISPLAY "Enter first number:"
INPUT firstNumber
DISPLAY "Enter second number:"
INPUT secondNumber
DISPLAY "Choose operation: +, -, *, /"
INPUT operation
SWITCH operation
CASE "+":
SET result = firstNumber + secondNumber
DISPLAY "Result: " + result
CASE "-":
SET result = firstNumber - secondNumber
DISPLAY "Result: " + result
CASE "*":
SET result = firstNumber * secondNumber
DISPLAY "Result: " + result
CASE "/":
IF secondNumber != 0 THEN
SET result = firstNumber / secondNumber
DISPLAY "Result: " + result
ELSE
DISPLAY "Division by zero is not allowed"
END IF
DEFAULT:
DISPLAY "Invalid operation"
END SWITCH
END ENTRY POINT
The program checks the value of operation. If the operation is +, addition runs. If it is -, subtraction runs. If no operation matches, the default message is shown.
Example 2: Day Name from Day Number
This example displays the day name based on a number.
/*
This program displays day name using SWITCH.
*/
ENTRY POINT
DECLARE dayNumber AS INTEGER = 0
DISPLAY "Enter day number from 1 to 7:"
INPUT dayNumber
SWITCH dayNumber
CASE 1:
DISPLAY "Monday"
CASE 2:
DISPLAY "Tuesday"
CASE 3:
DISPLAY "Wednesday"
CASE 4:
DISPLAY "Thursday"
CASE 5:
DISPLAY "Friday"
CASE 6:
DISPLAY "Saturday"
CASE 7:
DISPLAY "Sunday"
DEFAULT:
DISPLAY "Invalid day number"
END SWITCH
END ENTRY POINT
Sample Output
Enter day number from 1 to 7:
3
Wednesday
Since the entered value is 3, the program runs the case for Wednesday.
Example 3: Menu-Based Program
Switch statements are very useful in menu-driven programs.
/*
This program handles menu selection using SWITCH.
*/
ENTRY POINT
DECLARE choice AS INTEGER = 0
DISPLAY "----- Main Menu -----"
DISPLAY "1. Add Student"
DISPLAY "2. View Student"
DISPLAY "3. Update Student"
DISPLAY "4. Delete Student"
DISPLAY "5. Exit"
DISPLAY "Enter your choice:"
INPUT choice
SWITCH choice
CASE 1:
DISPLAY "Add Student selected"
CASE 2:
DISPLAY "View Student selected"
CASE 3:
DISPLAY "Update Student selected"
CASE 4:
DISPLAY "Delete Student selected"
CASE 5:
DISPLAY "Exit selected"
DEFAULT:
DISPLAY "Invalid menu choice"
END SWITCH
END ENTRY POINT
Each menu number maps to a specific action. This is easier to read than a long else-if ladder for fixed menu choices.
Example 4: User Role Matching
A switch or match statement can also be used to choose actions based on user role.
/*
This program displays access level based on user role.
*/
ENTRY POINT
DECLARE userRole AS TEXT = ""
DISPLAY "Enter user role:"
INPUT userRole
MATCH userRole
CASE "admin":
DISPLAY "Access granted to admin dashboard"
CASE "teacher":
DISPLAY "Access granted to teacher dashboard"
CASE "student":
DISPLAY "Access granted to student dashboard"
CASE "guest":
DISPLAY "Access granted to guest area"
DEFAULT:
DISPLAY "Unknown role"
END MATCH
END ENTRY POINT
In this example, MATCH checks the role value and runs the matching block.
Switch / Match vs Else-If Ladder
Switch / match statements and else-if ladders are both used for decision making, but they are useful in different situations.
| Feature | Switch / Match | Else-If Ladder |
|---|---|---|
| Best For | Multiple fixed choices | Multiple conditions or ranges |
| Example | choice == 1, choice == 2 |
marks >= 90, amount >= 5000 |
| Readability | Very readable for menu options and fixed values | Readable for ranges and complex conditions |
| Condition Type | Usually matches one expression against many cases | Can compare different expressions and complex conditions |
| Common Use | Menus, days, operations, roles, status codes | Grades, discounts, validation ranges |
When to Use Switch / Match
Use switch or match when the program compares one value against multiple fixed choices.
Good Use Cases
- Menu selection.
- Calculator operation selection.
- Day number to day name conversion.
- Month number to month name conversion.
- User role selection.
- Status code handling.
- Command selection.
- Category-based action selection.
When Not to Use Switch / Match
Switch or match may not be the best choice when conditions involve ranges, multiple unrelated variables, or complex logical checks.
Prefer Else-If Ladder When
- You need to check ranges such as
marks >= 90. - You need different conditions for different variables.
- You need complex logical operators such as
ANDandOR. - You need validation such as
age >= 18 AND hasVoterID == true. - The conditions are not fixed choices.
Default Case
The DEFAULT case is used when no case matches the expression.
SWITCH choice
CASE 1:
DISPLAY "Start"
CASE 2:
DISPLAY "Settings"
CASE 3:
DISPLAY "Exit"
DEFAULT:
DISPLAY "Invalid choice"
END SWITCH
The default case is useful because it handles unexpected or invalid input.
Break / Exit Concept
In some programming languages, a matched case needs a break or exit instruction to stop execution from continuing into the next case.
Since this course is language-neutral, students should understand the concept as:
CASE value:
Run this case
Exit the switch after this case
Without proper exit behavior in languages that require it, the program may continue executing later cases unexpectedly.
Language-Neutral Switch with Exit Concept
SWITCH choice
CASE 1:
DISPLAY "Option 1 selected"
EXIT SWITCH
CASE 2:
DISPLAY "Option 2 selected"
EXIT SWITCH
CASE 3:
DISPLAY "Option 3 selected"
EXIT SWITCH
DEFAULT:
DISPLAY "Invalid option"
END SWITCH
The EXIT SWITCH idea represents stopping after the matched case.
Trace Table for Switch Example
Let us trace a menu-based switch statement.
SWITCH choice
CASE 1:
DISPLAY "Add"
CASE 2:
DISPLAY "View"
CASE 3:
DISPLAY "Exit"
DEFAULT:
DISPLAY "Invalid"
END SWITCH
| choice | Matched Case | Output |
|---|---|---|
1 |
CASE 1 |
Add |
2 |
CASE 2 |
View |
3 |
CASE 3 |
Exit |
9 |
DEFAULT |
Invalid |
How Switch / Match Helps Debugging
Switch or match statements make debugging easier because cases are clearly separated.
Debugging Questions
- What value is being checked?
- Which case should match?
- Is there a case for every expected value?
- Is the default case handling invalid input?
- Is the matched case executing correctly?
- Does the program stop after the matched case when required?
- Are case values unique?
- Would an else-if ladder be better for this logic?
Common Beginner Mistakes
Mistakes
- Using switch for range-based conditions.
- Forgetting the default case.
- Forgetting to stop after a matched case in languages that require break.
- Using duplicate case values.
- Making each case too long and difficult to read.
- Using switch when else-if would be clearer.
- Not validating user input before switch.
- Not testing invalid values.
Better Habits
- Use switch for fixed choices.
- Use default for unmatched values.
- Keep each case short and focused.
- Use meaningful case labels.
- Use clear output messages.
- Test every case.
- Test the default case.
- Choose else-if ladder for ranges and complex conditions.
Best Practices for Switch / Match Statement
Good switch or match logic should be clean, readable, and suitable for fixed choices.
Recommended Practices
- Use switch or match when checking one value against many cases.
- Use clear and unique case values.
- Add a default case for invalid or unexpected values.
- Keep each case block short.
- Use meaningful variable names such as
choice,operation, oruserRole. - Use switch for menus and operation selection.
- Use else-if ladder for ranges and complex conditions.
- Test all valid cases.
- Test invalid input.
- Use proper indentation for readability.
Prerequisites Before Learning Switch / Match Statement
To understand switch and match statements properly, students should already know these concepts:
Basic Prerequisites
- What is control flow?
- Sequential execution.
- Decision making.
- Simple
IFstatement. IF ELSEstatement.- Else-if ladder.
- Variables and data types.
- Comparison operators.
- Input and output.
- Basic input validation.
Practice Activity: Complete the Switch Statement
Complete the following pseudocode to display calculator operation names.
INPUT operation
SWITCH operation
CASE "+":
DISPLAY "Addition"
CASE "-":
DISPLAY "Subtraction"
CASE "*":
DISPLAY "________________"
CASE "/":
DISPLAY "________________"
DEFAULT:
DISPLAY "Invalid operation"
END SWITCH
Sample Answer
INPUT operation
SWITCH operation
CASE "+":
DISPLAY "Addition"
CASE "-":
DISPLAY "Subtraction"
CASE "*":
DISPLAY "Multiplication"
CASE "/":
DISPLAY "Division"
DEFAULT:
DISPLAY "Invalid operation"
END SWITCH
Mini Quiz
What is a switch statement?
A switch statement is a decision-making structure that selects one block of code from many possible cases based on the value of an expression.
What is the purpose of a case?
A case represents one possible value or option that can match the expression.
What is the purpose of the default case?
The default case runs when none of the listed cases match the expression.
When should switch or match be used?
Switch or match should be used when one value needs to be compared against multiple fixed choices.
Give one example where switch is useful.
A calculator choosing between addition, subtraction, multiplication, and division is a good example of switch usage.
Interview Questions on Switch / Match Statement
Define switch statement in programming.
A switch statement is a control-flow structure that checks an expression and executes the code block matching one of its cases.
How is switch different from else-if ladder?
Switch is best for fixed choices based on one expression, while an else-if ladder is better for ranges and complex conditions.
Why is the default case useful?
The default case handles unexpected or invalid values when no case matches.
What is a match statement?
A match statement is a decision-making structure that chooses a block based on matching a value or pattern.
Can switch be used for calculator operations?
Yes. Switch is very useful for calculator operations because each operation symbol can be handled as a separate case.
Quick Summary
| Concept | Meaning |
|---|---|
| Switch Statement | Selects one block from many cases based on an expression. |
| Match Statement | Selects one block based on a matching value or pattern. |
| Case | A possible matching option. |
| Default | Runs when no case matches. |
| Best Use | Menus, operations, days, roles, commands, and status values. |
| Best Practice | Use switch or match for fixed choices and else-if ladder for complex conditions. |
Final Takeaway
Switch / Match statements help programs choose one action from many possible choices in a clean and readable way. They are best used when one value is compared against several fixed options. In the Programming Mastery Course, students should understand switch and match as structured decision-making tools that make menu-based and option-based programs easier to write, read, and maintain.