You could simplify the switch by making use of the isalpha() function.
The function returns a nonzero integer if the character that's passed as the argument is an alphabetic character, and it will return 0 (false) if the character isn't alphabetic.
You could therefore produce the same result as the previous switch with the following code:
#include <stdio.h> #include <ctype.h> int main()//from w ww. j av a2s .co m { char ch = 'a'; if (!isalpha(ch)) printf("The character is not a letter.\n"); else { switch (tolower(ch)) { case 'a': case 'e': case 'i': case 'o': case 'u': printf("The character is a vowel.\n"); break; default: printf("The character is a consonant.\n"); break; } } return 0; }
The if statement tests for ch not being a letter, and if this is so, it outputs a message.
If ch is a letter, the switch statement will sort out whether it is a vowel or a consonant.
The five vowel case values produce one output, and the default case produces the other.
ctype.h header also declares several other useful functions for testing a character.
Function | Tests For |
---|---|
islower() | Lowercase letter |
isupper() | Uppercase letter |
isalnum() | Uppercase or lowercase letter or a decimal digit |
iscntrl() | Control character |
isprint() | Any printing character including space |
isgraph() | Any printing character except space |
isdigit() | Decimal digit ( '0' to '9') |
isxdigit() | Hexadecimal digit ( '0' to '9', 'A' to 'F', 'a' to 'f') |
isblank() | Standard blank characters (space, '\t') |
isspace() | Whitespace character (space, '\n', '\t', '\v', '\r', '\f') |
ispunct() | Printing character for which isspace() and isalnum() return false |
isalpha() | Uppercase or lowercase letter |
tolower() | Convert to lowercase |
toupper() | Convert to uppercase |