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
- Read a string into
s1and initializecount = 0. - Loop from 0 to
s1.length() - 1. - Extract each character using
s1.at(i). - Check if the character matches any upper or lower case vowels using the Logical OR (
||) operator. - Increment
countif a match is found. - 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 syntaxs1[i]) to extract and inspect each character individually against our vowel list.
Complexity
Time Complexity
O(n)
Space Complexity
O(1)