Exercise:
Write a C Program to check whether a character is a vowel or consonant.
Click Here to View the Solution!
#include <ctype.h>
#include <stdio.h>
int main() {
char c;
int lowercase_vowel, uppercase_vowel;
printf("Enter an alphabet: ");
scanf("%c", &c);
//Checks if variable c is a lowercase vowel
lowercase_vowel = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
//Checks if variable c is a uppercase vowel
uppercase_vowel = (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U');
// Show error message if c is not an alphabet
if (!isalpha(c)) {
printf("Error! Entered Character is Non-alphabetic.");
}
else if (lowercase_vowel || uppercase_vowel) {
printf("%c is a vowel.", c);
}
else {
printf("%c is a consonant.", c);
}
return 0;
}
Click Here to View the Output!
Enter an alphabet: e
e is a vowel.
Click Here to View the Explanation!
- This program is used to determine whether the entered character is a vowel or a consonant.
- In
main()
, the program requests the user to enter an alphabet and store in thecharacter variable c
using thescanf()
function. - Two integer type variables
lowercase_vowels
anduppercase_vowels
are initialized. - The
lowercase_vowel
returns true if the entered character is a lowercase vowel. Similarly, theuppercase_vowel
returns true ifc
is a upper case vowel. - In an
if...else statement
, a functionisalpha()
is used that initially checks that whetherc
is an alphabet. It then checks ifc
is either a lowercase or an uppercase vowel. If it is neither, the control goes to theelse statement
that prints that thec
is a consonant. - The
return 0 statement
is used to exit the program execution.