C++ Program to count Vowels in a string using Pointer
Last Updated :
27 Sep, 2019
Pre-requisite: Pointers in C++
Given a string of lowercase english alphabets. The task is to count number of vowels present in a string using pointers
Examples:
Input : str = "geeks"
Output : 2
Input : str = "geeksforgeeks"
Output : 5
Approach:
- Initialize the string using a character array.
- Create a character pointer and initialize it with the first element in array of character (string).
- Create a counter to count vowels.
- Iterate the loop till character pointer find ‘\0’ null character, and as soon as null character encounter, stop the loop.
- Check whether any vowel is present or not while iterating the pointer, if vowel found increment the count.
- Print the count.
Below is the implementation of the above approach:
#include <iostream>
using namespace std;
int vowelCount( char *sptr)
{
int count = 0;
while ((*sptr) != '\0' ) {
if (*sptr == 'a' || *sptr == 'e' || *sptr == 'i'
|| *sptr == 'o' || *sptr == 'u' ) {
count++;
}
sptr++;
}
return count;
}
int main()
{
char str[] = "geeksforgeeks" ;
cout << "Vowels in above string: " << vowelCount(str);
return 0;
}
|
Output:
Vowels in above string: 5
Share your thoughts in the comments
Please Login to comment...