codescracker


c

C Program to count Consonants, Vowels, Digits, Spaces etc. in String



« C Tutorial C Examples »

Here we will learn about how to create a program in C that asks from the user to enter any string at run-time, to count total number of:

present inside the given string. Here is the program:

// Write a program in C to count the following in a given sentence:
//  [A] All characters
//  [B] Upper case character
//  [C] Lower case character
//  [D] Digits
//  [E] Vowels
//  [F] Space character
//  [G] Words
//  [H] Lines
//  [I] Consonant
// -----------codescracker.com-----------

#include<stdio.h>
#include<conio.h>
int main()
{
    char str[100];
    int i, count=0, countChar=0;
    int countUpper=0, countLower=0, countDigit=0, countVowel=0;
    int countSpace=0, countWord=0, countLine=0, countConsonant=0;
    printf("Enter any string: ");
    gets(str);
    for(i=0; str[i]!='\0'; i++)
    {
        if(str[i]>=65 && str[i]<=90)
        {
            countUpper++;

        }
        else if(str[i]>=97 && str[i]<=122)
        {
            countLower++;
        }
        else if(str[i]>=48 && str[i]<=57)
            countDigit++;
        else if(str[i]==' ')
            countSpace++;
        else if(str[i]=='\n')
            countLine++;
        if(str[i]=='a' || str[i]=='e' || str[i]=='i' || str[i]=='o' ||
           str[i]=='u' || str[i]=='A' || str[i]=='E' || str[i]=='I' ||
           str[i]=='O' || str[i]=='U')
            countVowel++;
        if(str[i]!=' ')
            count++;
        else
        {
            if(count!=0 && str[i+1]!='\0')
                countWord++;
            count = 0;
        }
        countChar++;
    }
    countConsonant = (countUpper+countLower) - countVowel;
    printf("\nTotal Character = %d", countChar);
    printf("\nTotal Uppercase Character = %d", countUpper);
    printf("\nTotal Lowercase Character = %d", countLower);
    printf("\nTotal Vowel = %d", countVowel);
    printf("\nTotal Consonant = %d", countConsonant);
    printf("\nTotal Digit = %d", countDigit);
    printf("\nTotal Space = %d", countSpace);
    printf("\nTotal Word = %d", countWord+1);
    printf("\nTotal Line = %d", countLine);
    getch();
    return 0;
}

The program was written under Code::Blocks IDE, therefore here is the sample run after successful build and run. This is the first snapshot:

c count vowels consonants spaces digits

Now supply any string say Hello, this is program no.62 on codescracker and press ENTER key to see the following output. Here is the second snapshot of the sample run:

count digits vowels consonants spaces c

Here are the list of some main steps used in above program:


« C Tutorial C Examples »






Tools
Calculator

Quick Links
Signup - Login - Give Online Test