Introduction
Programming में decision making बहुत important होती है, जहाँ हमें किसी condition के आधार पर अलग-अलग actions perform करने होते हैं।
अब तक हमने if और if-else statements देखे, जो simple conditions के लिए उपयोगी होते हैं। लेकिन जब हमें कई conditions (multiple choices) को handle करना होता है, तब if-else को बार-बार लिखना program को लंबा और complex बना देता है।
ऐसी situations में C language हमें एक बेहतर और साफ तरीका देती है, जिसे switch statement कहते हैं।
switch statement का उपयोग तब किया जाता है जब:
- एक variable की value के आधार पर कई cases में से एक चुनना हो
- menu-driven programs बनाना हो
- fixed values के लिए decision लेना हो
यह program को readable, structured और efficient बनाता है।
Definition
switch statement एक multi-way decision making statement है, जो किसी expression की value के आधार पर different cases में से एक case को execute करता है।
Syntax
switch (expression)
{
case value1:
// statements
break;
case value2:
// statements
break;
default:
// statements
}
Important Points
- expression का result integer या character होना चाहिए
- हर case के बाद break लगाना जरूरी होता है
- break न लगाने पर next cases भी execute हो जाते हैं (fall-through)
- default case optional होता है
Example 1: Simple Number Check
#include <stdio.h>
int main()
{
int num = 2;
switch (num)
{
case 1:
printf("One");
break;
case 2:
printf("Two");
break;
case 3:
printf("Three");
break;
default:
printf("Invalid");
}
return 0;
}
Output:
Two
Example 2: Menu Driven Program
#include <stdio.h>
int main()
{
int choice;
printf("1. Add\n2. Subtract\n3. Exit\n");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("Addition Selected");
break;
case 2:
printf("Subtraction Selected");
break;
case 3:
printf("Exit");
break;
default:
printf("Invalid Choice");
}
return 0;
}
Example 3: Character Input
#include <stdio.h>
int main()
{
char ch = 'A';
switch (ch)
{
case 'A':
printf("Excellent");
break;
case 'B':
printf("Good");
break;
default:
printf("Average");
}
return 0;
}
Example 4: Without break
#include <stdio.h>
int main()
{
int num = 1;
switch (num)
{
case 1:
printf("One ");
case 2:
printf("Two ");
case 3:
printf("Three ");
} return 0;
}
Output:
One Two Three
Explanation:
- break नहीं है → सभी cases execute हो गए
Real Understanding
switch statement का उपयोग इन situations में होता है:
- menu driven programs
- option selection (user choice)
- fixed input handling (जैसे grades, options)
Difference: switch vs if-else
| switch | if-else |
|---|---|
| Multiple fixed values के लिए | Complex conditions के लिए |
| Faster और readable | Flexible लेकिन लंबा |
| Equality check करता है | कोई भी condition check कर सकता है |
Exam Points
- switch multi-way decision making statement है
- break बहुत important है
- default optional होता है
- fall-through concept exam में पूछा जाता है
- expression integer या char होना चाहिए