What is Switch/Case Logic?
Switch/Case is a control flow structure that allows a program to choose between multiple execution paths based on the value of a single expression. It is often used as a cleaner alternative to long chains of if-else-if
conditions.
When Should You Use Switch/Case?
Use switch-case when:
- You have a single variable or expression to compare against multiple constant values
- You want cleaner and more readable code than multiple if-else-if statements
- You’re performing similar actions for multiple values
Basic Syntax of Switch/Case (Pseudocode)
switch (expression) {
case value1:
// statements for value1
break
case value2:
// statements for value2
break
...
default:
// default statements
}
Example 1: Grading System
Let’s say we want to print a message based on a student's grade.
grade = "B"
switch (grade) {
case "A":
print("Excellent!")
break
case "B":
print("Good Job")
break
case "C":
print("You passed")
break
case "D":
print("Try harder next time")
break
default:
print("Invalid grade")
}
Output:
Good Job
Why is the break
Statement Important?
If break
is omitted, the program will continue executing the next cases even if a match is found. This behavior is called fall-through.
Example 2: Demonstrating Fall-Through
day = 2
switch (day) {
case 1:
print("Monday")
case 2:
print("Tuesday")
case 3:
print("Wednesday")
default:
print("Another day")
}
Output:
Tuesday Wednesday Another day
Question:
Why did the above example print multiple days?
Answer: Because we didn’t use break
after each case. Once the matching case (case 2) was found, all subsequent cases were executed.
Example 3: Using Default as a Fallback
fruit = "Banana"
switch (fruit) {
case "Apple":
print("Apples are red or green")
break
case "Orange":
print("Oranges are juicy")
break
default:
print("Unknown fruit")
}
Output:
Unknown fruit
Best Practices for Switch/Case
- Always include
break
unless you intentionally want fall-through - Use
default
to handle unexpected or unknown values - Switch statements are best for discrete, constant values (like enums, days, grades, etc.)
Questions to Build Intuition
Q1: Can you use switch-case for checking if a number is greater than 10?
Answer: No. Switch-case is used for comparing exact values, not for conditions like greater than
or less than
. For such comparisons, use if-else
.
Q2: What happens if two cases have the same value?
Answer: It's usually a syntax error in most programming languages. Each case must have a unique value.
Q3: Can you use strings in switch-case?
Answer: Some programming languages allow strings in switch-case (like modern C++, Java, Python 3.10+ with match-case), but this depends on the language. In pseudocode, yes — as we did in the examples above.