In this C program we are going to count Number of Vowels, Consonants, Digits, White spaces and Special characters in a given string.
Description:v – Vowels : a, e, i, o, u.
c – Consonants : Other than vowels. (b, c, d, f…)
d – Digits : 0 to 9.
ws – White space.
sc – Special characters : !, @, #, $, %….
Algorithm: To count Number of Vowels, Consonants, Digits, White spaces and Special characters
STEP 1: STARTSTEP 2: SET the values of all quantities to zero
vowels = 0, consonants = 0, digits = 0
white spaces = 0, special characters = 0
STEP 3: READ a string from keyboard
READ str
STEP 4: CONVERT the string to lower case
strlwr(str)
STEP 5: FIND the length of string
n = strlen(str)
STEP 6: REPEAT the steps 7 to 11 till END OF STRING reached
LOOP from i = 0 to END OF STRING
STEP 7: CHECK if the character is vowel
if character = vowel
INCREAMENT the value of vowel
v = v + 1
STEP 8: CHECK if the character is alphabet
if character = alphabet
INCREAMENT the value of alphabet
a = a + 1
Find number of consonants
c = a – v
STEP 9: CHECK if the character is digit
if character = digit
INCREAMENT the value of digit
d = d + 1
STEP 10: CHECK if the character is whit space
if character = space
INCREAMENT the value of space
ws = ws + 1
STEP 11: CALCULATE special character
sc = n – v – c – d – ws
STEP 12: PRINT number of vowels, consonants, digits, spaces, special characters
PRINT v, c, d, ws, sc
STEP 13: END
C Program: To count Number of Vowels, Consonants, Digits, White spaces and Special characters
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char str[500];
int v=0,a=0,c=0,d=0,ws=0,sc=0,n;
printf("Enter a string:\n");
gets(str);
strlwr(str);
n=strlen(str);
for (int i = 0; str[i] != '\0'; ++i)
{
if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i' ||str[i] == 'o' || str[i] == 'u')
v++;
if (str[i] >= 'a' && str[i] <= 'z')
a++;
c=a-v;
if(str[i] >= '0' && str[i] <= '9')
d++;
if(str[i] == ' ')
ws++;
sc=n-v-c-d-ws;
}
printf("Vowels: %d", v);
printf("\nConsonants: %d", c);
printf("\nDigits: %d", d);
printf("\nWhite spaces: %d", ws);
printf("\nSpecial characters: %d", sc);
getch();
return 0;
}
Output:
Enter a string:I Can – Tutorials@2021%
Vowels: 6
Consonants: 7
Digits: 4
White spaces: 3
Special characters: 3