Count The Number Of Vowels And Consonants In A String In C Program
Identifying and counting vowels and consonants within a given string is a common programming task that tests fundamental string manipulation and character classification skills. This operation is useful in various text processing applications, from linguistic analysis to data validation.
In this article, you will learn how to efficiently count the number of vowels and consonants in a string using the C programming language.
Problem Statement
The core challenge is to process a given string and determine the occurrences of vowels (A, E, I, O, U, case-insensitive) and consonants (any other English alphabet character) while ignoring non-alphabetic characters like spaces, numbers, or symbols. Accurately categorizing each character is crucial for a correct count.
Example
Consider the input string "Programming in C". The expected output for this string would be:
- Vowels: 6
- Consonants: 11
Background & Knowledge Prerequisites
To understand this solution, readers should be familiar with:
- C Basics: Fundamental syntax, variable declaration, and basic I/O operations.
- Strings in C: How strings are represented as character arrays and terminated by a null character (
\0). - Loops: Using
fororwhileloops to iterate through characters in a string. - Conditional Statements:
if-elsestructures for making decisions based on character types. - Character Functions: Basic usage of functions from the
library, specificallyisalpha()to check if a character is an alphabet andtolower()to convert a character to lowercase.
Use Cases or Case Studies
Counting vowels and consonants can be applied in several practical scenarios:
- Linguistic Analysis: Determining the phonetic structure of words or sentences for speech recognition or language learning tools.
- Text Statistics: Providing basic statistical insights into text documents, useful for readability scores or content analysis.
- Data Validation: Ensuring input strings meet specific criteria, such as containing a certain ratio of alphabetic characters.
- Educational Software: Creating exercises for students learning about word structure and phonetics.
- Simple Text Games: Developing word-based games that require character classification.
Solution Approaches
This problem is best solved by iterating through the string character by character and applying logical checks.
Approach 1: Iterative Character Check
This approach involves traversing the string from beginning to end. For each character, it first checks if it's an alphabet. If it is, the character is converted to lowercase for case-insensitive comparison, and then checked if it's a vowel. If not a vowel but an alphabet, it's counted as a consonant.
// Count Vowels and Consonants
#include <stdio.h>
#include <string.h> // For strlen()
#include <ctype.h> // For isalpha() and tolower()
int main() {
// Step 1: Declare and initialize a string and counters
char str[100];
int vowels = 0;
int consonants = 0;
int i;
// Step 2: Prompt user for input
printf("Enter a string: ");
fgets(str, sizeof(str), stdin); // Read string including spaces
// Remove trailing newline character if present from fgets
str[strcspn(str, "\\n")] = 0;
// Step 3: Iterate through the string
for (i = 0; str[i] != '\\0'; i++) {
// Step 4: Check if the character is an alphabet
if (isalpha(str[i])) {
// Step 5: Convert to lowercase for case-insensitive check
char ch = tolower(str[i]);
// Step 6: Check if it's a vowel
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowels++;
} else {
// Step 7: If not a vowel, it's a consonant
consonants++;
}
}
}
// Step 8: Print the results
printf("Number of vowels: %d\\n", vowels);
printf("Number of consonants: %d\\n", consonants);
return 0;
}
Sample Output
Enter a string: Programming in C
Number of vowels: 6
Number of consonants: 11
Stepwise Explanation for Clarity
- Include Headers:
-
stdio.h: For standard input/output functions likeprintfandfgets.
-
string.h: Provides strcspn to remove the trailing newline character from fgets input.ctype.h: Essential for isalpha() (checks if a character is an alphabet) and tolower() (converts character to lowercase).- Initialize Variables: A character array
strstores the input string, andvowelsandconsonantsintegers are initialized to zero to count occurrences. - Read Input:
fgetsis used to read the string, which is safer thanscanf("%s", ...)as it can handle strings with spaces. Thestrcspnline then removes the newline character thatfgetsincludes. - Loop Through String: A
forloop iterates through each character of the string until the null terminator (\0) is encountered. - Check for Alphabet: Inside the loop,
isalpha(str[i])verifies if the current character is an English alphabet (A-Z or a-z). Non-alphabetic characters are simply skipped. - Convert to Lowercase: If the character is an alphabet,
tolower(str[i])converts it to its lowercase equivalent. This ensures that both 'A' and 'a' are treated the same when checking for vowels, simplifying the comparison logic. - Identify Vowel or Consonant:
- An
ifstatement checks if the lowercase character matches any of the five vowels ('a', 'e', 'i', 'o', 'u'). If it does, thevowelscounter is incremented.
- An
consonants counter is incremented.- Print Results: After the loop completes, the final counts of vowels and consonants are printed to the console.
Conclusion
Counting vowels and consonants in a string using C is a fundamental exercise that combines string traversal, conditional logic, and character manipulation functions. The iterative character check approach provides a clear and efficient way to achieve this by systematically examining each character and categorizing it based on whether it is an alphabet, a vowel, or a consonant.
Summary
- Problem: Count English vowels and consonants in a string, ignoring non-alphabetic characters.
- Approach: Iterate through the string, character by character.
- Key Functions: Use
isalpha()fromto check if a character is an alphabet andtolower()for case-insensitive comparisons. - Logic: If an alphabet, check if it's 'a', 'e', 'i', 'o', 'u' (vowel), otherwise it's a consonant.
- Benefits: Simple, direct, and efficient for most string lengths.