C++

Finding The Number Of Vowels And Consonants In A String With A C++ Program

This application counts the number of vowels and consonants in a string that the user has entered.

Example: A program to count and show how many vowels and consonants are present in a given string

In this software, the user-entered string is stored in a char array, and in the for loop, vowels and consonants are counted. You must familiarize yourself with the C++ principles of arrays and for loops in order to comprehend this program.

#include <iostream>
using namespace std;
int main(){
   char str[100];
   int vowelCounter = 0, consonantCounter = 0;
   cout << "Enter any string: ";
   cin.getline(str, 150);
   //'\0 represent end of string
   for(int i = 0; str[i]!='\0'; i++) {
      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')
      {
         vowelCounter++;
      }
      else if((str[i]>='a'&& str[i]<='z') || (str[i]>='A'&& str[i]<='Z'))
      {
         consonantCounter++;
      }
   }
   cout << "Vowels in String: " << vowelCounter << endl;
   cout << "Consonants in String: " << consonantCounter << endl;
   return 0;
}

Output:

Enter any string: Hello Guys, Welcome to Beginnersbook.com
Vowels in String: 13
Consonants in String: 21

The identical application may be created in C++ by employing Strings. In the example above, change the following line of code to use a string instead of a char array:

char str[100];
int vowelCounter = 0, consonantCounter = 0;
cout << "Enter any string: ";
cin.getline(str, 150);

with this code:

string str;
int vowelCounter = 0, consonantCounter = 0;

cout << "Enter any string: ";
getline(cin, str);

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button