Count the Number of Vowels and Consonants in a Char Array
To count the number of vowels and consonants in a character array in C, we iterate through the array and check each character. If the character is a vowel (a, e, i, o, u), we increment the vowel count; otherwise, if it is an alphabetic consonant, we increment the consonant count. This approach ensures that we accurately classify each letter.
Examples to Count Vowels and Consonants
1. Counting Vowels and Consonants in a Character Array
In this example, we will take a predefined character array and iterate through it to count the vowels and consonants.
main.c
</>
Copy
#include <stdio.h>
#include <ctype.h>
int main() {
char str[] = "Hello World";
int vowels = 0, consonants = 0;
for (int i = 0; str[i] != '\0'; i++) {
char ch = tolower(str[i]);
if (ch >= 'a' && ch <= 'z') {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
vowels++;
else
consonants++;
}
}
printf("Vowels: %d\n", vowels);
printf("Consonants: %d\n", consonants);
return 0;
}
Explanation:
- We declare a character array
str[]
with the string"Hello World"
. - Two integer variables,
vowels
andconsonants
, are initialized to zero. - We iterate through the array using a
for
loop until we reach the null terminator'\0'
. - Each character is converted to lowercase using
tolower()
to simplify comparison. - If the character is an alphabetic letter, we check if it is a vowel (
a, e, i, o, u
) or a consonant. - The respective counter (
vowels
orconsonants
) is incremented accordingly.
Output:
Vowels: 3
Consonants: 7
2. Counting Vowels and Consonants from User Input
In this example, we will take a string input from the user and count the number of vowels and consonants.
main.c
</>
Copy
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int vowels = 0, consonants = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
for (int i = 0; str[i] != '\0'; i++) {
char ch = tolower(str[i]);
if (ch >= 'a' && ch <= 'z') {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
vowels++;
else
consonants++;
}
}
printf("Vowels: %d\n", vowels);
printf("Consonants: %d\n", consonants);
return 0;
}
Explanation:
- We declare a character array
str[100]
to store user input. - We prompt the user to enter a string and store it using
fgets()
. - A
for
loop iterates through the input string until the null terminator'\0'
is encountered. - The character is converted to lowercase using
tolower()
for case insensitivity. - If the character is a vowel, we increment the
vowels
counter; otherwise, if it’s a consonant, we increment theconsonants
counter.
Output Example:
Enter a string: AppleBanana
Vowels: 5
Consonants: 6
Conclusion
In this tutorial, we explored different ways to count vowels and consonants in a character array in C:
- Predefined Character Array: Iterated through a hardcoded string and counted vowels and consonants.
- User Input: Allowed the user to enter a string and performed the same count dynamically.