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
Show 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