Count Vowels and Consonants in a String in C
Strings are sequences of characters in C, and manipulating them is a fundamental skill in programming. One common task is to count the number of vowels and consonants present in a string. This helps in text analysis, input validation, and understanding string handling in C.
This tutorial demonstrates how to count vowels and consonants in a string using simple C programs with step-by-step explanation and examples.
Problem Statement
Write a C program to count the number of vowels and consonants in a given string.
Algorithm
Step 1: Start the program.
Step 2: Include `stdio.h` and `ctype.h` for input/output and character functions.
Step 3: Declare a string array to store input and variables to count vowels and consonants.
Step 4: Input the string from the user using `fgets()` for safe input.
Step 5: Traverse each character in the string using a loop.
Step 6: For each character:
- Convert the character to lowercase to simplify comparison.
- If the character is a vowel (a, e, i, o, u), increment the vowel counter.
- Else if the character is an alphabet letter, increment the consonant counter.
Step 7: After the loop ends, print the total number of vowels and consonants.
Step 8: End the program.
C Program to Count Vowels and Consonants
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main() {
char str[200];
int vowels = 0, consonants = 0;
int i;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
if(str[strlen(str)-1] == '\n') str[strlen(str)-1] = '\0';
for(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("Number of vowels: %d\n", vowels);
printf("Number of consonants: %d\n", consonants);
return 0;
}
Example Input/Output
Input: Enter a string: Hello World Output: Number of vowels: 3 Number of consonants: 7
Notes
- The program uses `fgets()` instead of `gets()` for safe input.
- The `tolower()` function converts uppercase letters to lowercase to simplify vowel checking.
- Only alphabetic characters are counted as vowels or consonants; spaces, numbers, and special characters are ignored.
- The program can handle both uppercase and lowercase letters.
Conclusion
Counting vowels and consonants in a string is an excellent way to practice string manipulation and loops in C. This program can be extended to count digits, special characters, or even implement case-insensitive frequency analysis.
Codecrown