Algorithm
-
Initialize Variables:
- Create a variable
inputString
to store the input string. - Create a variable
vowelCount
and set it to 0 to keep track of the count of vowels.
- Create a variable
-
Input:
- Accept the input string from the user or use a predefined string.
-
Convert to Lowercase:
- Convert the entire input string to lowercase to make the matching case-insensitive.
-
Iterate Through Characters:
- Use a loop to iterate through each character in the string.
-
Check for Vowels:
- For each character, check if it is a vowel (a, e, i, o, u).
- You can use a conditional statement (if-else) or a switch statement to check for each vowel.
-
Increment Count:
- If the character is a vowel, increment the
vowelCount
variable by 1.
- If the character is a vowel, increment the
-
Output Result:
- After the loop completes, output or display the value of
vowelCount
as the result.
- After the loop completes, output or display the value of
Code Examples
#1 Code Example- Count the Number of Vowels Using Regex
Code -
Javascript Programming
// program to count the number of vowels in a string
function countVowel(str) {
// find the count of vowels
const count = str.match(/[aeiou]/gi).length;
// return number of vowels
return count;
}
// take input
const string = prompt('Enter a string: ');
const result = countVowel(string);
console.log(result);
Copy The Code &
Try With Live Editor
Output
Enter a string: JavaScript program
5
5
#2 Code Example- Count the Number of Vowels Using for Loop
Code -
Javascript Programming
// program to count the number of vowels in a string
// defining vowels
const vowels = ["a", "e", "i", "o", "u"]
function countVowel(str) {
// initialize count
let count = 0;
// loop through string to test if each character is a vowel
for (let letter of str.toLowerCase()) {
if (vowels.includes(letter)) {
count++;
}
}
// return number of vowels
return count
}
// take input
const string = prompt('Enter a string: ');
const result = countVowel(string);
console.log(result);
Copy The Code &
Try With Live Editor
Output
Enter a string: JavaScript program
5
5
Demonstration
JavaScript Programing Example to Count the Number of Vowels in a String-DevsEnv