Write a program to count the vowels and letters in free text given as standard input. Read a text character at a time until you encounter end-of-data.

Source Code

Brief explanation is provided after the source code.

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

int main(int argc, char **argv) {
    char c;
    int vowel = 0, letter = 0;
    while ( (c = getchar()) != EOF) {
        if ( c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ||
             c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U')
            vowel++;
        if ( !isspace(c) && !isdigit(c) && !ispunct(c) && c != '\n')
            letter++;
    }
    printf("Vowel(s): %d\n", vowel);
    printf("Letter(s): %d\n", letter);
    return 0;
}

When you compile and execute the above program it produces the following result on Linux:

I am the greatest in 2015
Vowel(s): 7
Letter(s): 16

Brief Explanation

  • The program starts by initializing variables vowel and letter to zero.
  • Using a while loop, a character is read from a free text at a time up to the end-of-file (crtl+D) and checked whether it is a vowel and a letter. If the character matches any of the letters a, e, i, o, u or the cap's version, then it is a vowel. If it is neither a space (determine by function isspace), or digit (determine by function isdigit) or punctuation (determine by function ispunct), then it is a letter.
  • Using the function printf, the number of vowels and letters are printed to the stdout.

Add comment


Security code
Refresh