C switch-case Statement – A Smart Alternative to else-if Ladder
The switch-case statement in C is used to execute different blocks of code based on the value of a variable or expression. It’s a great alternative to using multiple else-if statements, especially when you’re checking for equality against constants.
#include <stdio.h>
int main() {
int choice;
printf("1. Add\n2. Subtract\n3. Multiply\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("You chose Add.\n");
break;
case 2:
printf("You chose Subtract.\n");
break;
case 3:
printf("You chose Multiply.\n");
break;
default:
printf("Invalid choice.\n");
}
return 0;
}
Output:
1. Add 2. Subtract 3. Multiply
Enter your choice: 2
You chose Subtract.
Example 2 – Days of the Week
#include <stdio.h>
int main() {
int day = 4;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
case 4:
printf("Thursday\n");
break;
case 5:
printf("Friday\n");
break;
case 6:
printf("Saturday\n");
break;
case 7:
printf("Sunday\n");
break;
default:
printf("Invalid day\n");
}
return 0;
}
When to Use switch-case
Use when:
Comparing one variable to many constant values
You want clearer, faster code than an if-else-if chain
Avoid When:
Comparing ranges or complex conditions
Working with non-integer types (in older C versions)