switch–case Statement in C Language
What is switch–case?
switch–case is a decision-making statement used when:
- You want to check ONE variable
- Against multiple fixed values
- And execute only one matching block of code
Instead of writing many else if conditions, we use switch–case to make the code:
- Cleaner
- Faster
- More readable
Why switch–case after else if?
else if ladder | switch case |
| Works with ranges & conditions | Works with fixed values |
| Slower for many checks | Faster & cleaner |
| Long and messy sometimes | Very readable |
Rule to remember:
- Use
else if→ when you have ranges / conditions - Use
switch–case→ when you have fixed options
How switch–case Works?
- Takes one variable
- Compares it with each case
- Executes the matching case
breakstops further executiondefaultruns if no case matches (optional)
Image Scenario Recap (Very Simple)
Menu on board:
1 → Coffee
2 → Tea
3 → BurgerEcho says:
“Can I have number 2?”
Cashier:
- Checks the number
- Finds 2
- Gives Tea
- Stops checking further
This is switch–case in real life.
Program Example (C Language)
c
1#include <stdio.h>
2int main() {
3 int choice = 2; // Echo says: "number 2"
4
5 switch (choice) {
6 case 1:
7 printf("Coffee");
8 break;
9 case 2:
10 printf("Tea");
11 break;
12 case 3:
13 printf("Burger");
14 break;
15 default:
16 printf("Invalid choice");
17 }
18 return 0;
19}How switch–case Works?
Step 1: One decision is taken
int choice = 2;Echo chooses one number only
Step 2: Switch checks the number
switch (choice)Cashier looks at the number once
Step 3: Case matching happens
case 1:Not matching → skip
case 2:Result:
Match found
Cashier says: “Here is your Tea”
Step 4: break stops everything
break;Cashier stops checking further items
(No Coffee + Burger together 😄)
When Echo Says: “Can I have number 5?”
int choice = 5;No case matches → goes to:
default:
printf("Invalid choice");Key Points to Remember
switchworks with one variablecasevalues must be constantbreakprevents fall-throughdefaultis optional but recommended- Best for menu-driven programs
