Count the Number of Vowels in a String
This C program counts the number of vowels in a given string. The vowels are ‘a’, ‘e’, ‘i’, ‘o’, ‘u’ (both uppercase and lowercase).
Program Structure and Explanation
The program follows these steps:
- Define a function to count the vowels in the given string.
- Prompt the user to enter a string.
- Call the function and display the result.
Code:
#include <stdio.h>
#include <string.h>
// Function to count the number of vowels in a string
int countVowels(char *str) {
int count = 0;
char c;
// Iterate through the string character by character
for (int i = 0; str[i] != ‘\0’; i++) {
c = str[i];
// Convert to lowercase if the character is uppercase
if (c >= ‘A’ && c <= ‘Z’) {
c = c + ‘a’ – ‘A’;
}
// Check if the character is a vowel
if (c == ‘a’ || c == ‘e’ || c == ‘i’ || c == ‘o’ || c == ‘u’) {
count++;
}
}
return count;
}
int main() {
char str[100];
// Prompt the user to enter a string
printf(“Enter a string: “);
fgets(str, sizeof(str), stdin);
// Remove the newline character from the string
str[strcspn(str, “\n”)] = ‘\0’;
// Count the vowels in the string
int vowelCount = countVowels(str);
// Display the result
printf(“Number of vowels: %d\n”, vowelCount);
return 0;
}
Explanation:
- The
countVowels
function takes a string as input and iterates through each character. - It converts any uppercase character to lowercase to simplify vowel checking.
- The function checks if the character is a vowel (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) and increments the count if true.
- In the
main
function, the user is prompted to enter a string. Thefgets
function is used to read the input string. - The newline character from the input is removed using
strcspn
. - The
countVowels
function is called, and the result is displayed.