Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to count all the vowel in a string

C++ Code Example — String Programs

ADVERTISEMENT

WAP to count all the vowel in a string

Objective

Write a C++ program to count all the vowels in a given string.

Algorithm / Approach

  1. Read a string into s1 and initialize count = 0.
  2. Loop from 0 to s1.length() - 1.
  3. Extract each character using s1.at(i).
  4. Check if the character matches any upper or lower case vowels using the Logical OR (||) operator.
  5. Increment count if a match is found.
  6. Print the final count.
main.cpp
#include<iostream>
using namespace std;
int main() {
 string s1;
 int count =0;
 cout<<"Enter a string : ";
 getline(cin,s1);
 for(int i = 0; i< s1.length(); i++) {
  char x = s1.at(i);
  if(x=='A' ||x=='E'||x=='I'||x=='O'
  ||x=='U'||x=='a'||x=='e'||x=='i'
  ||x=='o'||x=='u') {
 count++;
  }
 }
 cout<<"Vowels = "<< count<< endl;
 return 0;
}

Expected Output

Enter a string : cprowess
Vowels = 2

Explanation of the Program

  • Strings can be treated like arrays of characters.
  • By looping through the length of the string, we can use the .at(i) function (or standard array syntax s1[i]) to extract and inspect each character individually against our vowel list.

Complexity

Time Complexity O(n)
Space Complexity O(1)
ADVERTISEMENT