Code Example of Switch Statement in C++/Java

#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

  1. Include Libraries: Include the necessary header file for input/output operations.
  2. Namespace: Use the std namespace to avoid having to prepend std:: to standard functions and objects.
  3. Main Function: Define the main function as the entry point of the program.
  4. Variable Declaration: Declare an integer variable choice to store the user input.
  5. User Input: Prompt the user to enter a number and store it in the choice variable.
  6. Switch Statement: Use a switch statement to perform different actions based on the value of choice.
  7. Case 1: If choice is 1, output "You chose 1" and break out of the switch statement.
  8. Case 2: If choice is 2, output "You chose 2" and break out of the switch statement.
  9. Case 3: If choice is 3, output "You chose 3" and break out of the switch statement.
  10. Default Case: If choice does not match any of the cases, output "Invalid choice".
  11. Return: Return 0 to indicate successful execution of the program.