Switch Case Logic in Programming



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:

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")
}
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")
}
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")
}
Unknown fruit

Best Practices for Switch/Case

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.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You 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.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M