C Example Code2026-03-202 min read
Write a C program to count vowels, consonants, digits, and whitespace in a string using standard ctype.h classification functions.
Character Classification Logic
To count vowels and consonants accurately:
- Traverse the string character by character until the null terminator
\0. - Convert each character to lowercase using
tolower(). - Check if it matches
a, e, i, o, u(vowels). - If it is an alphabetic character but not a vowel, count it as a consonant.
C Source Code
c (ISO Standard)#include <stdio.h> #include <ctype.h> void countCharacters(const char *str, int *vowels, int *consonants, int *digits, int *spaces) { *vowels = *consonants = *digits = *spaces = 0; for (int i = 0; str[i] != '\0'; i++) { char ch = tolower((unsigned char)str[i]); if (ch >= 'a' && ch <= 'z') { if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') { (*vowels)++; } else { (*consonants)++; } } else if (isdigit((unsigned char)str[i])) { (*digits)++; } else if (isspace((unsigned char)str[i])) { (*spaces)++; } } } int main() { const char text[] = "Modern C23 Standard Edition 2026"; int v, c, d, s; countCharacters(text, &v, &c, &d, &s); printf("Input Text: \"%s\"\n\n", text); printf(" Vowels: %d\n", v); printf(" Consonants: %d\n", c); printf(" Digits: %d\n", d); printf(" Spaces: %d\n", s); return 0; }
Sample Output
text (ISO Standard)Input Text: "Modern C23 Standard Edition 2026" Vowels: 9 Consonants: 15 Digits: 6 Spaces: 4
Complexity Analysis
- Time Complexity:
O(n)where n is string length. - Space Complexity:
O(1)constant memory overhead.
Related Programs
- Reverse character strings in String Reverse in C.
- Review standard library functions in C Standard Library Functions.