C program to count Vowels, Consonants and digits in a String

              String is a collection of characters. This program counts the vowels present in the input string, consonants appear in the input and numbers available in the string.

Let us implement it in C language.

              This program reads the input string from the user using fgets() function.

  • Using a for loop, each character is separated. Each character is checked whether it is an alphabet or a digit.
  • If it is a digit, the count of digit variable is increased by one.
  • If it is an alphabet, the alphabet is converted as lowercase.
  • It is compared with vowels. If it a vowel, vowel count is increased.
  • Otherwise, consonant count is increased.
  • Finally, each count is displayed.

C Code:

#include <stdio.h>

#include <ctype.h> 

//It has built-in function to check the characters and numbers

int main() {

    char s[100];

    int v_str = 0, c_str = 0, d_str = 0;

    printf("Enter a string: ");

    fgets(s, sizeof(s), stdin);  //input reading

    for (int i = 0; s[i] != '\0'; i++) {

        char ch = s[i];

        if (isdigit(ch)) {

            d_str++;

        } else if (isalpha(ch)) {

            ch = tolower(ch);  // convert it into lowercase

            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')

                v_str++;

            else

                c_str++;

        }

    }

    printf("Vowels of the String: %d\n", v_str);

    printf("Consonants: %d\n", c_str);

    printf("Digits: %d\n", d_str);

    return 0;

}

Output:

Enter a string: Hi, this is the C program2

Vowels of the String: 6

Consonants: 13

Digits: 1

Yes. The program is successful. Hope, you understood it. Keep Coding!!!

Comments

Popular posts from this blog

How to create a XML DTD for displaying student details

File handling in C++

Employee record management in C