In: Computer Science
Write a subroutine that will receive a char input
value. This subroutine should then use a switch statement to
determine if the char is a vowel, consonant, digit, or other type
of character.
Write the subroutine only,
This is in C++
The C++ code to find the given character is vowel or consonant or special character or a number is:
#include<iostream>
#include<cstring>
using namespace std;
//Determine() function checks if the char ch is
// a vowel or consonant or number or special character
// This function returns nothing
void Determine(char ch){
//Checking if the char is a number using ascii values
//ch-0 gives ascii value of character in ch
//Ascii values of digits are 48 to 57
if(ch-0>=48 && ch-0<=57){
ch=1;
}
//If ch is not a number or alphabet, then any other ascii value
//is a special character
if((ch-0<=48 || ch-0>=57) && (ch-0<=97 || ch-0>=122) && (ch-0<=65 || ch-0>=90)){
ch=2;
}
//Using switch case to determine and print appropriate result
switch (ch)
{
//for case a e i o u printing vowels.
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
cout<<"Entered character is a vowel"<<endl;
break;
//We checked for digits using ascii values and
//assigned ch=1 if ch is a digit
//so for case 1 we need to print its a number
case 1:
cout<<"Entered character is a number"<<endl;
break;
case 2:
cout<<"Entered character is a special character"<<endl;
break;
default:
cout<<"Entered character is a Consonant"<<endl;
break;
}
}
int main(){
//Declaring a variable of type char
//char variables can store only one character
char ch;
//Promprint for input and reading a character
//Remember, if you enter a word instead of char
//Compiler wont throw a error, instead it stores first char of word
cout<<"Enter a character: ";
cin>>ch;
//Calling Determine() function to determine
//if ch is vowel or consonant or other
Determine(ch);
}
I have used ascii values to check for numbers and speacial characters. Then using a switch case first I checked for a,e,i,o,u cases and printed vowel if true, if false based on previous checks I wrote cases to print if it is a number or special character.
I have provided comments in the program explaining the process and the functions used. I have tested the code for all possible cases and validated the outputs.
I am sharing few output screenshots for your reference.
Let us see what will be the output if we try to enter a word as input:
As you can see, the compiler didn't throw any exception, instead it took the first letter of the word and stored in ch. So we got output as consonant.
Hope this answer helps you.
Thank you.