Display the number of vowels in a given character array using pointers

Program to display the number of vowels in a given character array using pointers is discussed here. Let us consider a sample character array: faceprep. The number of vowels is 3 and consonants is 5.

The algorithm to display the number of vowels is as given below:

  • Read a string as input from the user.
  • Assign the address of the string to the character pointer.
  • Increment the pointer when the character is a vowel.

Program to display the number of vowels in a given character array

// C program to display the count of vowels in a given character array

#include
int main()
{
char str[100]; // characer array
char *ptr;  // pointer
int cntV,cntC;  // variables to store the count of vowels and sonsonants

printf(“Enter a string: “);
gets(str);

ptr=str;  // Assign the character array to the pointer

cntV=cntC=0;
while(*ptr!=’\0′)  // Check if the scanned character is a vowel
{
if(*ptr==’A’ ||*ptr==’E’ ||*ptr==’I’ ||*ptr==’O’ ||*ptr==’U’ ||*ptr==’a’ ||*ptr==’e’ ||*ptr==’i’ ||*ptr==’o’ ||*ptr==’u’)
cntV++;   // increment vowel count
else
cntC++;  // increment consonant count
ptr++;    // Increment the pointer to scan the next character
}

printf(“Total number of vowels : %d\nTotal number of consonants : %d\n”,cntV,cntC);
return 0;

// C++ program to display the count of vowels in a given character array

#include <iostream>
using namespace std;
int main()
{
char str[100]; // characer array
char *ptr; // pointer
int cntV,cntC; // variables to store the count of vowels and sonsonants

cout << “Enter a string: “;
cin >> str;

ptr=str; // Assign the character array to the pointer

cntV=cntC=0;
while(*ptr!=’\0′) // Check if the scanned character is a vowel
{
if(*ptr==’A’ ||*ptr==’E’ ||*ptr==’I’ ||*ptr==’O’ ||*ptr==’U’ ||*ptr==’a’ ||*ptr==’e’ ||*ptr==’i’ ||*ptr==’o’ ||*ptr==’u’)
cntV++; // increment vowel count
else
cntC++; // increment consonant count
ptr++; // Increment the pointer to scan the next character
}

cout << “Total number of vowels : ” << cntV << “\nTotal number of consonants : ” << cntC << endl;
return 0;
}

Output:

display the number of vowels in a character array.

Time complexity: O(n)

Input the string from the user. Assign the input character array to the pointer. Scan all the input characters. If it is a vowel, increment the cntV variable and if it is a consonant, increment the cntC variable. After all the characters are scanned, display the total number of vowels and consonants.