⬅ Previous Topic
Nested Conditions - Multi-Level Decision MakingNext Topic ⮕
Truthy and Falsy Values⬅ Previous Topic
Nested Conditions - Multi-Level Decision MakingNext Topic ⮕
Truthy and Falsy ValuesSwitch/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.
Use switch-case when:
switch (expression) {
case value1:
// statements for value1
break
case value2:
// statements for value2
break
...
default:
// default statements
}
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")
}
Good Job
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.
day = 2
switch (day) {
case 1:
print("Monday")
case 2:
print("Tuesday")
case 3:
print("Wednesday")
default:
print("Another day")
}
Tuesday Wednesday Another day
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.
fruit = "Banana"
switch (fruit) {
case "Apple":
print("Apples are red or green")
break
case "Orange":
print("Oranges are juicy")
break
default:
print("Unknown fruit")
}
Unknown fruit
break
unless you intentionally want fall-throughdefault
to handle unexpected or unknown valuesAnswer: No. Switch-case is used for comparing exact values, not for conditions like greater than
or less than
. For such comparisons, use if-else
.
Answer: It's usually a syntax error in most programming languages. Each case must have a unique value.
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.
⬅ Previous Topic
Nested Conditions - Multi-Level Decision MakingNext Topic ⮕
Truthy and Falsy ValuesYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.