Switch Case
Programming
This program demonstrates the switch statement, which provides an efficient way to select one of many code blocks to execute based on a variable's value.
Implementation
#include <iostream>
int main() {
int choice;
std::cout << "Enter a number (1-3): ";
std::cin >> choice;
switch (choice) {
case 1:
std::cout << "You chose 1" << std::endl;
break;
case 2:
std::cout << "You chose 2" << std::endl;
break;
case 3:
std::cout << "You chose 3" << std::endl;
break;
default:
std::cout << "Invalid choice" << std::endl;
}
return 0;
} Key Concepts
switch: Evaluates an expression and matches it to a case labelcase: Defines a specific value to matchbreak: Exits the switch statement (prevents fall-through to next case)default: Handles values that don't match any case (optional)
Example Interaction
Enter a number (1-3): 2
You chose 2