Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to count number of vowels and consonants in a string in C Language?
In C programming, counting vowels and consonants in a string is a common string manipulation task. We iterate through each character and check if it's a vowel (a, e, i, o, u) or consonant using conditional statements.
Syntax
// Check if character is vowel
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U')
vowels++;
else if(isalpha(ch))
consonants++;
Method 1: Using Character Comparison
This approach checks each character against all vowel possibilities and counts alphabetic non-vowels as consonants −
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int i, vowels, consonants;
i = vowels = consonants = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
while (str[i] != '\0') {
if (isalpha(str[i])) {
if (str[i] == 'A' || str[i] == 'E' || str[i] == 'I' ||
str[i] == 'O' || str[i] == 'U' || str[i] == 'a' ||
str[i] == 'e' || str[i] == 'i' || str[i] == 'o' ||
str[i] == 'u') {
vowels++;
} else {
consonants++;
}
}
i++;
}
printf("Vowels: %d
", vowels);
printf("Consonants: %d
", consonants);
return 0;
}
Enter a string: TutorialsPoint Vowels: 6 Consonants: 8
Method 2: Using Switch Statement
A cleaner approach using switch-case for vowel detection −
#include <stdio.h>
#include <ctype.h>
int main() {
char str[] = "Programming";
int i, vowels = 0, consonants = 0;
printf("String: %s
", str);
for (i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) {
switch (tolower(str[i])) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
vowels++;
break;
default:
consonants++;
break;
}
}
}
printf("Vowels: %d
", vowels);
printf("Consonants: %d
", consonants);
return 0;
}
String: Programming Vowels: 3 Consonants: 8
Key Points
- Use
isalpha()to check if a character is alphabetic before counting - The
tolower()function simplifies vowel checking by converting to lowercase - Non-alphabetic characters (spaces, digits, symbols) are ignored in the count
- Always use
fgets()instead ofgets()for safe string input
Conclusion
Counting vowels and consonants in C involves iterating through the string and using conditional logic to categorize alphabetic characters. The switch-case method provides cleaner code for vowel detection.
Advertisements
