Count the Number of Vowels in a String in C++

In this exercise, you will write a C++ function that counts how many vowels are present in a given string. Vowel detection is a common task in string manipulation, text analysis, and natural language processing. By completing this exercise, you'll reinforce your understanding of loops, conditionals, character comparison, and string traversal in C++.

The function should be able to handle both lowercase and uppercase vowels, and return the total count of vowels found in the input string. This will help you practice character comparisons and improve your handling of textual data.

This is a beginner-friendly task that also builds up foundational logic used in more advanced string operations.

Group

Functions in C++

Objective

1. Define a function that takes a string as input.
2. Loop through each character of the string.
3. Check if the character is a vowel (either lowercase or uppercase).
4. Count the number of vowels and return or display the result.

Create a function that counts the number of vowels in a string.

Example C++ Exercise

 Copy C++ Code
#include <iostream> // Include the iostream library for input and output
#include <string>   // Include the string library to work with strings

using namespace std; // Use the standard namespace

// Function to count the number of vowels in a string
int countVowels(string text) {
    int count = 0; // Initialize the vowel count to 0

    // Loop through each character in the string
    for (char ch : text) {
        // Convert character to lowercase for easier comparison
        ch = tolower(ch);

        // Check if the character is a vowel
        if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
            count++; // Increment the counter if a vowel is found
        }
    }

    return count; // Return the total number of vowels
}

// Main function
int main() {
    string input;

    // Prompt the user to enter a string
    cout << "Enter a string: ";
    getline(cin, input); // Read the full line of text

    // Call the function and display the number of vowels
    int vowels = countVowels(input);
    cout << "Number of vowels in the string: " << vowels << endl;

    return 0; // End of program
}

 Output

Enter a string: Hello World
Number of vowels in the string: 3

Share this C++ Exercise


More C++ Programming Exercises of Functions in C++

Explore our set of C++ Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C++. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C++.