Program to count vowels in a string (Iterative and Recursive)
Last Updated :
16 Feb, 2023
Improve
Given a string, count the total number of vowels (a, e, i, o, u) in it. There are two methods to count total number of vowels in a string.
- Iterative
- Recursive
Examples:
Input : abc de Output : 2 Input : geeksforgeeks portal Output : 7
1. Iterative Method:
Below is the implementation:
- C++
- Java
- Python3
- C#
- PHP
- Javascript
C++
// C++ program to count vowels in a string #include<iostream> using namespace std; // Function to check the Vowel bool isVowel( char ch) { ch = toupper (ch); return (ch== 'A' || ch== 'E' || ch== 'I' || ch== 'O' || ch== 'U' ); } // Returns count of vowels in str int countVowels(string str) { int count = 0; for ( int i=0; i<str.length(); i++) if (isVowel(str[i])) // Check for vowel ++count; return count; } // Main Calling Function int main() { //string object string str = "abc de" ; // Total numbers of Vowel cout << countVowels(str) << endl; return 0; } |
Java
Python3
C#
PHP
Javascript
Output
2
Time Complexity: O(n), where n is the length of the string
Auxiliary Space: O(1)
2. Recursive Method:
Below is the implementation:
- C++
- Java
- Python 3
- C#
- PHP
- Javascript
C++
// Recursive C++ program to count the total // number of vowels using recursion #include<iostream> using namespace std; // Function to check the Vowel bool isVowel( char ch) { ch = toupper (ch); return (ch== 'A' || ch== 'E' || ch== 'I' || ch== 'O' || ch== 'U' ); } // to count total number of vowel from 0 to n int countVovels(string str, int n) { if (n == 1) return isVowel(str[n-1]); return countVovels(str, n-1) + isVowel(str[n-1]); } // Main Calling Function int main() { // string object string str = "abc de" ; // Total numbers of Vowel cout << countVovels(str, str.length()) << endl; return 0; } |
Java
Python 3
C#
PHP
Javascript
Output
2
Time Complexity: O(n), where n is the length of the string
Auxiliary Space: O(n), where n is the length of the string since the function is calling itself n times.
How Recursive Code Working.