Google News
logo
C++ Program to find number of Vowels and Consonants in a String
In the following example of C++ program that finds the number of vowels and consonants in a string :
Program :
#include <iostream>
#include <string>

using namespace std;

int main() {
    string str;
    int vowels = 0, consonants = 0;

    cout << "Enter a string: ";
    getline(cin, str);

    for (int i = 0; i < str.length(); i++) {
        char ch = tolower(str[i]);
        if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
            vowels++;
        } else if (ch >= 'a' && ch <= 'z') {
            consonants++;
        }
    }

    cout << "The number of vowels in the string is: " << vowels << endl;
    cout << "The number of consonants in the string is: " << consonants << endl;

    return 0;
}
Output :
Enter a string: Welcome to freetimelearning.com

The number of vowels in the string is: 12

The number of consonants in the string is: 16
* This program prompts the user to enter a string, reads the input string using getline(), and then uses a for loop to iterate through each character in the string.

* For each character, it checks if it is a vowel (a, e, i, o, u) or a consonant (any other alphabetical character).

* It also converts the character to lowercase before checking to ensure that both uppercase and lowercase vowels are counted. Finally, it prints out the number of vowels and consonants in the string.