#include <iostream>
using namespace std;
int main() {
int choice;
cout << "Enter a number (1-3): ";
cin >> choice;
switch (choice) {
case 1:
cout << "You chose 1";
break;
case 2:
cout << "You chose 2";
break;
case 3:
cout << "You chose 3";
break;
default:
cout << "Invalid choice";
}
return 0;
}
Code Explanation
- Include Libraries: Include the necessary header file for input/output operations.
- Namespace: Use the std namespace to avoid having to prepend
std::
to standard functions and objects. - Main Function: Define the main function as the entry point of the program.
- Variable Declaration: Declare an integer variable
choice
to store the user input. - User Input: Prompt the user to enter a number and store it in the
choice
variable. - Switch Statement: Use a switch statement to perform different actions based on the value of
choice
. - Case 1: If
choice
is 1, output "You chose 1" and break out of the switch statement. - Case 2: If
choice
is 2, output "You chose 2" and break out of the switch statement. - Case 3: If
choice
is 3, output "You chose 3" and break out of the switch statement. - Default Case: If
choice
does not match any of the cases, output "Invalid choice". - Return: Return 0 to indicate successful execution of the program.