Count the Number of Vowels in a Given String

This program counts the number of vowels in a given string using C++.

Program Explanation

The program structure includes:

  • Input: A string entered by the user.
  • Process: Iterates through the string to count vowels.
  • Output: Displays the number of vowels in the string.

C++ Program


/**
 * Program to count the number of vowels in a given string.
 * 
 * This program reads a string from the user and counts the number
 * of vowels (a, e, i, o, u) in the string, regardless of case.
 */

#include <iostream>
#include <string>

using namespace std;

// Function to count vowels in a given string
int countVowels(const string& str) {
    int count = 0;
    for (char ch : str) {
        // Convert character to lowercase for case insensitivity
        char lowerCh = tolower(ch);
        // Check if the character is a vowel
        if (lowerCh == 'a' || lowerCh == 'e' || lowerCh == 'i' || lowerCh == 'o' || lowerCh == 'u') {
            count++;
        }
    }
    return count;
}

int main() {
    string inputString;
    
    // Prompt user for input
    cout << "Enter a string: ";
    getline(cin, inputString);
    
    // Count the number of vowels in the input string
    int vowelCount = countVowels(inputString);
    
    // Output the result
    cout << "Number of vowels in the given string: " << vowelCount << endl;
    
    return 0;
}

Documentation

Function: countVowels(const string& str)

  • Description: Counts the number of vowels in the given string.
  • Parameters: const string& str – the input string to be processed.
  • Returns: int – the number of vowels in the input string.

Function: int main()

  • Description: The main function of the program.
  • Process:
    • Prompts the user to enter a string.
    • Calls the countVowels function to count the number of vowels.
    • Displays the number of vowels found in the string.
  • Returns: int – exit status of the program (0 for successful execution).

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)