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).