C++ Code Example: advanced switch-case statement

This program is designed to take a single character as input from the user and determine if it is a vowel or consonant. Here’s a step-by-step explanation:

  1. The checkCharacter function is defined with a single parameter input, which is a char data type.
  2. The bool variable isVowel is declared and initialized to false.
  3. A switch statement is used to determine if the input character is a vowel (upper- or lowercase ‘a’, ‘e’, ‘i’, ‘o’, ‘u’). If any of these cases are matched, the isVowel variable is set to true.
  4. After the switch statement, an if statement is used to determine if the isVowel variable is true. If it is, the program outputs the message input is a vowel. If not, a nested if statement checks if the input is a letter between a and z or A and Z. If the input is a letter, the program outputs the message input is a consonant. If not, the program outputs the message error.
  5. In the main function, the user is prompted to enter a character. The entered character is stored in the input variable.
  6. The checkCharacter function is called with input as an argument.
  7. The program returns 0, indicating that it has executed successfully.
#include <iostream>
using namespace std;

void checkCharacter(char input) {
    bool isVowel = false;
    switch (input) {
        case 'a':
        case 'e':
        case 'i':
        case 'o':
        case 'u':
        case 'A':
        case 'E':
        case 'I':
        case 'O':
        case 'U':
            isVowel = true;
    }
    if (isVowel) {
        cout << input << " is a vowel" << endl;
    } else {
        if ((input >= 'a' && input <= 'z') || (input >= 'A' && input <= 'Z'))
            cout << input << " is a consonant" << endl;
        else
            cout << "error" << endl;
    }
}

int main() {
    char input;

    cout << "Please enter a character: ";
    cin >> input;

    checkCharacter(input);

    return 0;
}
Output 1
Please enter a character: a
a is a vowel
Output 2
Please enter a character: D
D is a consonant