Switch Statement in C
The switch statement in C is used for decision-making. It allows the program to execute a block of code when a specified case value is true and execute a different block when the condition is false.
The Switch statement is used for handling multiple conditions, similar to if-else if statements.
The difference in both is that if-else if can check multiple conditions, while switch checks one value against different cases.
Syntax:
case value1:
// Code to execute if expression == value1
break;
case value2:
// Code to execute if expression == value2
break;
default:
// Code to execute if no cases match
}
Example 1: Check Day of the Week
This program takes a number (1-7) as input and displays the corresponding day of the week using a switch statement.
#include <stdio.h> int main() { int day; printf("Enter a number (1-7) for the day of the week: "); scanf("%d", &day); 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 input!\n"); } return 0; }
Output:
Wednesday
Invalid input!
Example 2: Menu Selection Using Switch
This program displays a menu of food items and asks the user to enter a choice. Based on the selection, the program prints the corresponding item using a switch statement.
int main() {
int choice;
printf("Menu:\n");
printf("1. Pizza\n");
printf("2. Burger\n");
printf("3. Pasta\n");
printf("Enter your choice (1-3): ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("You selected Pizza.\n");
break;
case 2:
printf("You selected Burger.\n");
break;
case 3:
printf("You selected Pasta.\n");
break;
default:
printf("Invalid choice! Please select between 1-3.\n");
}
return 0;
}
Output:
1. Pizza
2. Burger
3. Pasta
Enter your choice (1-3): 2
You selected Burger.
Example 3: Simple Calculator Using Switch
This program takes two numbers and an operator as input and performs the corresponding arithmetic operation using a switch statement.
#include <stdio.h> int main() { int num1, num2, result; char op; printf("Enter first number: "); scanf("%d", &num1); printf("Enter an operator (+, -, *, /): "); scanf(" %c", &op); printf("Enter second number: "); scanf("%d", &num2); switch (op) { case '+': result = num1 + num2; printf("Result: %d\n", result); break; case '-': result = num1 - num2; printf("Result: %d\n", result); break; case '*': result = num1 * num2; printf("Result: %d\n", result); break; case '/': result = num1 / num2; printf("Result: %d\n", result); break; default: printf("Invalid operator! Please use +, -, *, or /.\n"); } return 0; }
Output:
Enter an operator (+, -, *, /): *
Enter second number: 5
Result: 50
Enter first number: 12
Enter an operator (+, -, *, /): %
Enter second number: 6
Invalid operator! Please use +, -, *, or /.