Skip to content
Devtoolry

Strings · beginner

C Program to Count Vowels and Consonants in a String

Count the vowels, consonants, digits and spaces in a string in C by looping until the null terminator and classifying each character with ctype.h.

Counting character types is a good exercise in walking a C string: loop until the terminating '\0' and classify each character. ctype.h has the tests for letters, digits and whitespace; strchr() checks whether a character is one of a set.

The program

C
#include <ctype.h>
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *text = "Programming in C, since 1972!";
    int vowels = 0, consonants = 0, digits = 0, spaces = 0;

    for (const char *p = text; *p != '\0'; p++) {
        unsigned char ch = (unsigned char)*p;
        if (isalpha(ch)) {
            if (strchr("aeiou", tolower(ch)))
                vowels++;
            else
                consonants++;
        } else if (isdigit(ch)) {
            digits++;
        } else if (isspace(ch)) {
            spaces++;
        }
    }
    printf("Vowels: %d, consonants: %d, digits: %d, spaces: %d\n", vowels, consonants, digits, spaces);
    return 0;
}
Output
Vowels: 6, consonants: 13, digits: 4, spaces: 4

How it works

  1. The pointer p walks through the string; *p is the current character and the loop stops at '\0'.
  2. isalpha() is true for letters. strchr("aeiou", tolower(ch)) returns a non-null pointer when the lowercase letter is a vowel.
  3. Other letters are consonants; isdigit() and isspace() count digits and whitespace.
  4. Punctuation such as the comma and "!" is not counted in any group.

Another way: Count each vowel separately

An int array indexed by letter (ch - 'a') counts every letter at once; the vowels are then read from it.

C
#include <ctype.h>
#include <stdio.h>

int main(void) {
    const char *text = "Programming in C";
    int counts[26] = {0};
    for (int i = 0; text[i]; i++) {
        unsigned char ch = (unsigned char)text[i];
        if (isalpha(ch))
            counts[tolower(ch) - 'a']++;
    }
    const char *vowels = "aeiou";
    for (int i = 0; vowels[i]; i++)
        printf("%c: %d\n", vowels[i], counts[vowels[i] - 'a']);
    return 0;
}
Output
a: 1
e: 0
i: 2
o: 1
u: 0

Common mistakes

  • Checking only lowercase vowels, so "A" and "E" are counted as consonants.
  • Counting every non-vowel as a consonant, including spaces, digits and punctuation.
  • strchr("aeiou", ch) also matches ch == '\0' (it finds the terminator); here that cannot happen because only letters reach it.

Try it yourself

  • Read a line with fgets() and count its vowels.
  • Print the most frequent letter in the text.

Open the program in the C Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.

Browse all 25 C examples, or write your own program in the online C Compiler.