Count the pairs of vowels in the given string in C++


We are given with a string of characters and the task is to calculate the count of pairs having both the elements as vowels. As we know there are five vowels in English alphabet i.e. a, i, e, o, u and other characters are known as Consonants.

Input − string str = "tutorials point”

Output − Count the pairs of vowels in the given string are: 2

Explanation − From the given string we can form pairs as (t, u), (u, t), (t, o), (o, r), (r, i), (i, a), (a, l), (l, s), (s, p), (p, o), (o, i), (i, n) and (n , t). So, the pairs with both the elements as vowels are (i, a) and (o, i) therefore the count of pairs of vowels is 2.

Input − string str = "learning”

Output − Count the pairs of vowels in the given string are: 1

Input −From the given string we can form pairs as (l, e), (e, a), (a, r), (r, n), (n, i), (i, n) and (n, g). So, the pairs with both the elements as vowels is (e, a) only therefore the count of pairs of vowels is 1.

Approach used in the below program is as follows

  • Input the string of characters in a string type variable

  • Calculate the length of a string using length() function that will return the total number of characters in a string

  • Take a temporary variable count to store the count of pairs of vowels.

  • Start loop For from i to 0 till the length of a string

  • Inside the loop, check IF str[i] is ‘a’ OR ‘i’ OR ‘e’ OR ‘o’ OR ‘u’ then check IF str[i+1] is ‘a’ OR ‘i’ OR ‘e’ OR ‘o’ OR ‘u’ then increment the value of count by 1

  • Return the count

  • Print the result

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int count_pairs(string str, int length){
   int count = 0;
   for(int i=0 ;i<length-1; i++){
      if(str[i]=='a' || str[i]=='i'||str[i]=='e'||str[i]=='o'||str[i]=='u'){
         if(str[i+1]=='a'||str[i+1]=='i'||str[i+1]=='e'||str[i+1]=='o'||str[i+1]=='u'){
            count++;
         }
      }
   }
   return count;
}
int main(){
   string str = "tutorials point";
   int length = str.length();
   cout<<"Count the pairs of vowels in the given string are: "<<count_pairs(str, length);
   return 0;
}

Output

If we run the above code it will generate the following output −

Count the pairs of vowels in the given string are: 2

Updated on: 02-Nov-2020

268 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements