Count the Number of Vowels, Consonants, Digits and Whitespaces in C

Exercise:

Write a C Program to count the number of vowels, consonants, digits and whitespaces.

Click Here to View the Solution!
#include <stdio.h>
int main() {
    char line[150];
    int vowels, consonant, digit, space;
    vowels = consonant = digit = space = 0;
    printf("Enter a line of string: ");
    fgets(line, sizeof(line), stdin);
    for (int i = 0; line[i] != '\0'; ++i) {
        if (line[i] == 'a' || line[i] == 'e' || line[i] == 'i' 
            ||line[i] == 'o'|| line[i] == 'u' || line[i] == 'A'
            || line[i] == 'E' || line[i] == 'I' || line[i] ==
            'O' || line[i] == 'U') {
            ++vowels;
        } 

        else if ((line[i] >= 'a' && line[i] <= 'z') || (line[i] >= 'A' && line[i] <= 'Z')) {
            ++consonant;
        } 

        else if (line[i] >= '0' && line[i] <= '9') {
            ++digit;
        } 

        else if (line[i] == ' ') {
            ++space;
        }
    }   
    printf("Vowels: %d", vowels);
    printf("\nConsonants: %d", consonant);
    printf("\nDigits: %d", digit);
    printf("\nWhite spaces: %d", space);
    return 0;
}
Click Here to View the Output!
Enter a line of string: This is a java
Vowels: 5
Consonants: 6
Digits: 0
White spaces: 3
Click Here to View the Explanation!
  • This program is used to count the number of vowels, consonants, digits and spaces in a string.
  • In main(), a string array line is declared of the size 150 along with integer type variables vowel, consonant, digit and space which are initialized to 0.
  • The program requests the user to enter a string which is then stored in line[150].
  • A for loop is initialized which iterates over the characters in the string. In every iteration, if…else…if statements are used which compare the characters of the strings with the conditions set in the statements and check whether the character is a vowel, consonant, digit or a space. For instance, if the character is a vowel, the value of the variable vowel is incremented by one.
  • After the loop ends, the values stored in the variables vowel, consonant, digit and space are printed.