Write A Program To Count The Number Of Vowels In A String In C Program
Counting vowels in a string is a fundamental programming task often used to demonstrate string manipulation and character processing in C. In this article, you will learn how to write a C program to accurately count the number of vowels in a given string.
Problem Statement
The core problem is to iterate through a sequence of characters (a string) and identify how many of them are vowels. A vowel is defined as 'a', 'e', 'i', 'o', 'u', and their uppercase counterparts ('A', 'E', 'I', 'O', 'U'). The program must be case-insensitive, meaning both 'A' and 'a' should be counted as one vowel.
Example
Consider the input string: "Programming Is Fun"
The vowels are: 'o', 'a', 'i', 'I', 'u'. The expected output for this string would be: 5 vowels.
Background & Knowledge Prerequisites
To understand the solutions presented, readers should have a basic understanding of:
- C Programming Basics: Variables, data types, operators.
- Strings in C: How strings are represented as arrays of characters and terminated by a null character (
\0). - Loops:
fororwhileloops for iterating over strings. - Conditional Statements:
if-else iforswitchstatements for character comparison. - Standard I/O: Using
printffor output andfgetsorscanffor input. - Character Functions: Basic usage of functions from
liketolower().
Relevant headers for these programs include:
-
for standard input/output functions likeprintfandfgets. -
for string manipulation functions likestrlen. -
for character classification and conversion functions liketolower.
Use Cases or Case Studies
Counting vowels can be useful in various scenarios:
- Text Analysis: Analyzing the linguistic structure of text, determining readability scores, or performing sentiment analysis.
- Educational Tools: Developing simple programs for language learning, such as tools that help identify vowels or consonant patterns.
- Basic Spell Checkers: As part of a larger system, vowel counts can contribute to evaluating word validity or suggesting corrections.
- Data Validation: In specific input fields, ensuring a minimum or maximum number of vowels might be a validation rule.
- Cryptography (simple cases): Analyzing patterns in encrypted messages, though this is a very basic form of analysis.
Solution Approaches
We will explore two common approaches to solve this problem: direct iteration and comparison, and using a helper function for improved modularity.
Approach 1: Direct Iteration and Comparison
This approach involves looping through each character of the string and directly checking if it matches any of the vowel characters, handling both uppercase and lowercase.
Summary: Iterate through the string character by character, convert each to lowercase, and check if it's one of 'a', 'e', 'i', 'o', 'u'.
// Count Vowels Direct Iteration
#include <stdio.h>
#include <string.h> // For strlen()
#include <ctype.h> // For tolower()
int main() {
// Step 1: Declare a character array (string) and a counter for vowels.
char str[100];
int vowelCount = 0;
int i; // Loop counter
// Step 2: Prompt the user to enter a string.
printf("Enter a string: ");
// Step 3: Read the string from the user.
// Using fgets to safely read a line of input including spaces.
// It includes the newline character, so we might need to handle it.
fgets(str, sizeof(str), stdin);
// Step 4: Remove the trailing newline character if it exists.
// strlen(str) returns length including newline if present.
str[strcspn(str, "\\n")] = 0;
// Step 5: Iterate through the string character by character.
for (i = 0; str[i] != '\\0'; i++) {
// Step 6: Convert the current character to lowercase for case-insensitive comparison.
char ch = tolower(str[i]);
// Step 7: Check if the lowercase character is a vowel.
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowelCount++;
}
}
// Step 8: Print the total count of vowels.
printf("Number of vowels in the string: %d\\n", vowelCount);
return 0;
}
Sample Output:
Enter a string: Hello World
Number of vowels in the string: 3
Stepwise Explanation:
- Include Headers:
stdio.hforprintfandfgets,string.hforstrcspn(to remove newline), andctype.hfortolower. - Declare Variables: A character array
strto hold the input string, an integervowelCountinitialized to 0, and a loop counteri. - Get Input:
fgetsis used to read the string safely, preventing buffer overflows. - Handle Newline:
fgetsincludes the newline character (\n) if the user presses Enter before the buffer is full.strcspnis used to find its position, and it's replaced with a null terminator (\0) to properly end the string. - Loop Through String: A
forloop iterates from the beginning of the string (i = 0) until the null terminator (\0) is encountered. - Convert to Lowercase: Inside the loop,
tolower(str[i])converts the current character to its lowercase equivalent. This simplifies the vowel check as only lowercase vowels need to be compared. - Check for Vowel: An
ifstatement checks if the lowercase characterchis equal to 'a', 'e', 'i', 'o', or 'u'. - Increment Count: If the character is a vowel,
vowelCountis incremented. - Print Result: After the loop finishes, the final
vowelCountis printed.
Approach 2: Using a Helper Function for Clarity
This approach refactors the vowel checking logic into a separate function, making the main function cleaner and the code more modular and reusable.
Summary: Create a isVowel function to check if a single character is a vowel. The main program then iterates through the string, calling isVowel for each character.
// Count Vowels Helper Function
#include <stdio.h>
#include <string.h> // For strlen()
#include <ctype.h> // For tolower()
// Function to check if a character is a vowel (case-insensitive)
int isVowel(char c) {
char lower_c = tolower(c); // Convert to lowercase
if (lower_c == 'a' || lower_c == 'e' || lower_c == 'i' || lower_c == 'o' || lower_c == 'u') {
return 1; // It's a vowel
}
return 0; // It's not a vowel
}
int main() {
// Step 1: Declare a character array (string) and a counter for vowels.
char str[100];
int vowelCount = 0;
int i; // Loop counter
// Step 2: Prompt the user to enter a string.
printf("Enter a string: ");
// Step 3: Read the string from the user.
fgets(str, sizeof(str), stdin);
// Step 4: Remove the trailing newline character if it exists.
str[strcspn(str, "\\n")] = 0;
// Step 5: Iterate through the string character by character.
for (i = 0; str[i] != '\\0'; i++) {
// Step 6: Call the helper function to check if the current character is a vowel.
if (isVowel(str[i])) {
vowelCount++;
}
}
// Step 7: Print the total count of vowels.
printf("Number of vowels in the string: %d\\n", vowelCount);
return 0;
}
Sample Output:
Enter a string: Programming
Number of vowels in the string: 3
Stepwise Explanation:
isVowelFunction:- This function takes a single character
cas input.
- This function takes a single character
c to lowercase using tolower().1 (true) if it's a vowel, and 0 (false) otherwise.mainFunction:- The structure is very similar to Approach 1, including declarations, input, and newline handling.
if statement with multiple || conditions, it now calls isVowel(str[i]).isVowel returns 1, vowelCount is incremented.Conclusion
Counting vowels in a string is a foundational string manipulation exercise in C. Both direct iteration and using a helper function provide effective solutions. The helper function approach, while slightly more verbose initially, enhances code readability, reusability, and maintainability, which are crucial for larger and more complex projects. Understanding these methods builds a strong base for more advanced text processing tasks.
Summary
- Counting vowels involves iterating through a string and identifying specific characters.
- Case-insensitivity is crucial, typically handled by converting characters to lowercase using
tolower()fromctype.h. - Approach 1: Direct Iteration involves a loop that checks each character against all lowercase vowels.
- Approach 2: Helper Function (
isVowel) encapsulates the vowel-checking logic, making the main loop cleaner and the code more modular. -
fgetsis recommended for safe string input, often requiring removal of the trailing newline character. - The fundamental logic relies on loops and conditional statements.