C Program to count vowels, digits, spaces, consonants using the string concepts

CServer Side ProgrammingProgramming

An array of characters (or) collection of characters is called a string.

Declaration

Refer the declaration given below −

char stringname [size];

For example − char a[50]; string of length 50 characters.

Initialization

The initialization is as follows −

  • Using single character constant −
char a[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}
  • Using string constants −
char a[10] = "Hello":;

Accessing

There is a control string “%s” used for accessing the string, till it encounters ‘\0’.

The logic used to count number of vowels is as follows −

if(string[i]=='a'||string[i]=='e'||string[i]=='i'||
   string[i]=='o'||string[i]=='u')//checking the char is vowel vowel=vowel+1;

The logic used to count number of digits is as follows −

if(string[i]=='0'||string[i]=='1'||string[i]=='2'||
string[i]=='3'||string[i]=='4'||string[i]=='5'||
string[i]=='6'||string[i]=='7'||string[i]=='8'||string[i]=='9')
digit=digit+1;

The logic used to count number of spaces is as follows −

if(string[i]==' ')
space=space+1;

Else, remaining all consonants.

Program

Following is the C Program to count vowels, digits, spaces, consonants by using the string concepts

 Live Demo

#include<stdio.h>
int main(){
   char string[50];
   int i,vowel=0,digit=0,space=0,consonant=0;
   printf("enter any string includes all types of characters:\n");
   gets(string);
   for(i=0;string[i]!='\0';i++){
      if(string[i]=='a'||string[i]=='e'||string[i]=='i'||
         string[i]=='o'||string[i]=='u')//checking the char is vowel vowel=vowel+1;
      else if(string[i]=='0'||string[i]=='1'||string[i]=='2'||
         string[i]=='3'||string[i]=='4'||string[i]=='5'||
         string[i]=='6'||string[i]=='7'||string[i]=='8'||string[i]=='9')
         digit=digit+1;
      else if(string[i]==' ')
         space=space+1;
      else
         consonant=consonant+1;
   }
   printf("vowel=%d\ndigit=%d\nspace=%d\nconsonant=%d\n",vowel,digit,space,consonant);
   return 0;
}

Output

The output is given below −

enter any string includes all types of characters:
Tutorials Point 1234 C programming 2020
vowel=9
digit=8
space=5
consonant=17
raja
Published on 10-Mar-2021 10:10:07
Advertisements