Count and print the number of vowels(a, e, i, o, u) in a given string


Program to count and print the number of vowels(a, e, i, o, u) in a given string

        This code can be simply executed with an if-else ladder. To know about the ladder statement in C++ read the if-else ladder in C++. 

        Take the string from the user, calculate the length of the string. Initiate a loop from zero to the size of the string and check each element is a vowel or not. If it is "a" increase the counter for a, if it is "e" increment the e counter similarly do for others. 

        Print the length and all the counters.


Code

#include <bits/stdc++.h>

using namespace std;


int main()

{

    cout<<"Enter a string"<<endl;

    

string s;                 //variable to store string

getline(cin,s);       //Reading the string


int l=s.length();           //finds the length of string



    //five counters to store count of a,e,i,o,u respectively


int c1=0,c2=0,c3=0,c4=0,c5=0;



for(int i=0; i<l; i++)           //loop checks each alphabets of a string

{


if(s[i]=='a' || s[i]=='A')           //if a increment c1

{

c1++;

}

else if(s[i]=='e' || s[i]=='E')            //if e increment c2

{

c2++;

}

else if(s[i]=='i' || s[i]=='I')            //if i increment c3

{

c3++;

}

else if(s[i]=='o' || s[i]=='O')             //if o increment c4

{

c4++;

}

else if(s[i]=='u' || s[i]=='U')             //if u increment c5

{

c5++;

}

}


//this block prints all the expected data


cout<<"The length of the string is "<<l<<endl;

cout<<"The a in string "<<c1<<endl;

cout<<"The e in string "<<c2<<endl;

cout<<"The i in string "<<c3<<endl;

cout<<"The o in string "<<c4<<endl;

cout<<"The u in string "<<c5<<endl;


    return 0;


}


Output

Enter a string

Coding Demons

The length of the string is 13

The a in string 0

The e in string 1

The i in string 1

The o in string 2

The u in string 0


Post a Comment

0 Comments