C Program to Count the Number of Vowels and Consonants in a Sentence
ADVERTISEMENTS
C program to count the number of vowels and consonants in a sentence.
In this article, you will learn how to count the number of vowels, consonants, digits, and white spaces in the input sentence.
To solve this problem we'll follow these criteria step by step to match counts
- Vowel - If a character is equal to these values
(a, e, i, o, u)
- Consonant - If a character = 'c',
(c >= 'a' && c <= 'z')
and c is not equal to these characters(a, e, i, o, u)
- Digit - If a character = 'c',
(c >= '0' && c <= '9')
- White Space - If a character is equal to
" "
Example
Enter a Sentance: Hello program
VOWELS:: 4
CONSONANTS:: 8
DIGITS:: 0
WHITE SPACES:: 1
You should know about the following topics in C programming to understand this program:
- C If-else statement
- C For loop
Source
// C Program to Count the Number of Vowels and Consonants
#include <stdio.h>
#include <ctype.h>
// It's the main function of the program
int main() {
int vowels = 0, consonants = 0, digits = 0, spaces = 0;
char sentance[1000];
// Step-1 Take input sentance from User
printf("Enter a Sentance: ");
fgets(sentance, sizeof(sentance), stdin);
// Step-2 Loop over the `sentance` variable to iterate the each character of the sentance
for (int i = 0; sentance[i] != '\0'; i++) {
sentance[i] = tolower(sentance[i]);
// Step-A If Character is a Vowel then increment `vowels` by 1
if (sentance[i] == 'a' || sentance[i] == 'e' || sentance[i] == 'i' || sentance[i] == 'o' || sentance[i] == 'u') {
vowels++;
}
// Step-B If Character is a Consonant then increment `consonants` by 1
else if (sentance[i] >= 'a' && sentance[i] <= 'z') {
consonants++;
}
// Step-C If Character is a digit then increment `digits` by 1
else if (sentance[i] >= '0' && sentance[i] <= '9') {
consonants++;
}
// Step-D If Character is empty space then increment `spaces` by 1
else if (sentance[i] == ' ') {
spaces++;
}
}
// Step-3 Final output of the program
printf("\nVOWELS:: %d\n", vowels);
printf("CONSONANTS:: %d\n", consonants);
printf("DIGITS:: %d\n", digits);
printf("WHITE SPACES:: %d\n", spaces);
return 0;
}
Output
Enter a Sentance: The sun set behind the mountains, painting the sky in hues of orange and pink
VOWELS:: 23
CONSONANTS:: 39
DIGITS:: 0
WHITE SPACES:: 14