Counting vowels and consonants in a string is a fundamental problem in C programming. It helps beginners understand string handling, character classification, and loop logic. By learning this program, you can also apply similar logic to analyze text, validate input, or create basic text-processing programs.
In this tutorial, we will write a complete C program to count vowels and consonants, explain each line of code, and provide alternative approaches. By the end, you will fully understand how to handle strings and classify characters in C.
What Are Strings?
Strings in C are arrays of characters ending with a null character \0
. Every character can be classified as a vowel, consonant, number, or special symbol. This program focuses on identifying vowels (a, e, i, o, u
in both lowercase and uppercase) and consonants (all other alphabetic characters).
Learning to classify characters strengthens your understanding of loops, conditionals, and the ctype.h
library functions. This program is often one of the first exercises for beginners to practice string handling in C.
Understanding the Problem
The goal is simple: given a string, count how many vowels and consonants it contains. To do this, we need to iterate over each character of the string, check whether it is a vowel or consonant, and keep a count.
We must also ignore digits, spaces, and special characters, as they are neither vowels nor consonants. This ensures the program only counts valid alphabetic letters.
Program 1: Using if-else
Statements
Before writing the program, we need to include standard libraries. stdio.h
is needed for input/output, and ctype.h
helps in character checks.
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int vowels = 0, consonants = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
for(int 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;
}
This program starts by declaring a character array to hold the string and two integer variables to count vowels and consonants. The fgets()
function reads a line of input safely.
We then use a for
loop to check each character. tolower()
converts each character to lowercase to simplify comparisons. The first if
ensures the character is alphabetic. Inside this, a nested if
checks if the character is a vowel. If it is, the vowel counter increases; otherwise, the consonant counter increases. Finally, the program prints the results.
Program 2: Using switch
Statement
An alternative approach uses the switch
statement to identify vowels.
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int vowels = 0, consonants = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
for(int i = 0; str[i] != '\0'; i++) {
char ch = tolower(str[i]);
if(ch >= 'a' && ch <= 'z') {
switch(ch) {
case 'a': case 'e': case 'i': case 'o': case 'u':
vowels++;
break;
default:
consonants++;
}
}
}
printf("Vowels: %d\n", vowels);
printf("Consonants: %d\n", consonants);
return 0;
}
The switch
version works similarly but may feel cleaner for some programmers. Each vowel is a separate case
. If the character does not match any vowel, it defaults to a consonant. The loop ensures every character is checked systematically.
Program 3: Using Functions for Modularity
For larger programs, modular code is better. We can create a function countVowelsConsonants()
to handle the counting.
#include <stdio.h>
#include <ctype.h>
void countVowelsConsonants(char str[], int *vowels, int *consonants) {
for(int 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)++;
}
}
}
int main() {
char str[100];
int vowels = 0, consonants = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
countVowelsConsonants(str, &vowels, &consonants);
printf("Vowels: %d\n", vowels);
printf("Consonants: %d\n", consonants);
return 0;
}
Using a function makes the code reusable. It accepts the string and pointers to the vowel and consonant counters. Each time we call the function, it updates the counts. This approach is cleaner for larger programs where multiple strings might be analyzed.
Program 4: Using Recursion
Recursion can also be used to process each character in a string. Instead of looping, the function calls itself with the next character until the end of the string is reached. This method is less common than iteration but demonstrates another way to solve the problem.
#include <stdio.h>
#include <ctype.h>
// Recursive function to count vowels and consonants
void countVowelsConsonants(char str[], int index, int *vowels, int *consonants) {
if (str[index] == '\0') {
return; // base case: end of string
}
char ch = tolower(str[index]);
if (ch >= 'a' && ch <= 'z') {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
(*vowels)++;
else
(*consonants)++;
}
countVowelsConsonants(str, index + 1, vowels, consonants); // recursive call
}
int main() {
char str[100];
int vowels = 0, consonants = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
countVowelsConsonants(str, 0, &vowels, &consonants);
printf("Vowels: %d\n", vowels);
printf("Consonants: %d\n", consonants);
return 0;
}
This recursive approach works by checking one character at a time and moving forward with each recursive call. When the end of the string is reached, the recursion stops. The counts for vowels and consonants are updated during the backtracking phase, giving the final result.
Performance Comparison
Different approaches have minor differences in performance:
Method | Time Complexity | Space Complexity | Notes |
---|---|---|---|
If-Else Statements | O(n) | O(1) | Simple and easy to understand |
Switch Statement | O(n) | O(1) | Cleaner code for vowels checking |
Function Approach | O(n) | O(1) | Modular, reusable, better for larger programs |
Recursion | O(n) | O(n) | Elegant, but higher space use due to recursive call stack |
All methods have linear time complexity with respect to the length of the string, and none require extra memory beyond the counters used for tracking vowels and consonants. Recursion introduces additional overhead due to function calls, but for short strings, this impact is negligible.
Which Method Should You Use?
For beginners, the if-else statement method is easiest to understand. It clearly shows how each character is classified as a vowel or consonant.
The switch statement is preferable if you want cleaner and readable code for handling vowels.
Using a function is ideal for modular programming, especially when analyzing multiple strings or integrating with larger projects. It keeps your main function tidy and makes the logic reusable.
FAQs
1. Can this program handle empty strings?
Yes. If the input string is empty, both vowels and consonants counters remain zero.
2. What about accented letters or non-English alphabets?
This program counts only standard English letters (a-z
, A-Z
). Accented letters or characters from other scripts are ignored.
3. Can I count digits and special characters separately?
Yes. You can add additional checks in the loop using isdigit()
or other ctype.h
functions.
4. Which method is faster?
All methods are linear in time complexity. For small strings, the difference is negligible. The function approach is slightly more modular but equally efficient.
Conclusion
Counting vowels and consonants in a string is a simple yet important exercise in C programming. It teaches how to handle strings, use loops, conditionals, and character functions effectively.
You learned three main approaches: if-else statements, switch-case, and modular functions. Each method has its own advantages. By practicing these programs, you will gain confidence in string processing, which is a core skill for many C programming tasks.
References & Additional Resources
A curated collection of textbooks, tutorials, and documentation for learning string manipulation and character handling in C.
- Kernighan, Brian W., and Dennis M. Ritchie. The C Programming Language, 2nd Edition, Prentice Hall, 1988 – The classic reference for C, covering strings, arrays, and character operations.
- GeeksforGeeks: Count Vowels and Consonants – Explains different approaches to count vowels and consonants in a string using C.
- Tutorialspoint: Strings in C – Overview of string declaration, initialization, and standard operations.
- Computer Science Tutorial: Character Handling Functions – Introduction to functions like
isalpha()
,isdigit()
, andtolower()
for text processing. - cplusplus.com: ctype.h Library – Official documentation for character classification and conversion functions in C.