C++ Program to count Vowels in a string using Pointer

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:

  1. Initialize the string using a character array.
  2. Create a character pointer and initialize it with the first element in array of charcter (string).
  3. Create a counter to count vowels.
  4. Iterate the loop till character pointer find ‘\0’ null character, and as soon as null character encounter, stop the loop.
  5. Check whether any vowel is present or not while iterating the pointer, if vowel found increment the count.
  6. Print the count.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to print count of
// vowels using pointers
  
#include <iostream>
  
using namespace std;
  
int vowelCount(char *sptr)
{
    // Create a counter
    int count = 0;
  
    // Iterate the loop until null character encounter
    while ((*sptr) != '\0') {
  
        // Check whether character pointer finds any vowels
        if (*sptr == 'a' || *sptr == 'e' || *sptr == 'i'
            || *sptr == 'o' || *sptr == 'u') {
  
            // If vowel found increment the count
            count++;
        }
  
        // Increment the pointer to next location
        // of address
        sptr++;
    }
  
    return count;
}
  
// Driver Code
int main()
{
    // Initialize the string
    char str[] = "geeksforgeeks";
  
    // Display the count
    cout << "Vowels in above string: " << vowelCount(str);
  
    return 0;
}

chevron_right


Output:

Vowels in above string: 5


My Personal Notes arrow_drop_up

सर्वशक्तिशाली इकलौता

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.