Count Vowels in a String

In this lesson, we will learn how to find the number of vowels in a string using recursion.

Problem Statement

We have to find the number of vowels in a given string. We know that the english alphabet contains 55 vowels: a,e,i,o,ua, e, i, o, u. Let’s solve this problem using both iterative and recursive method.

Iterative Method

To solve this problem we have to traverse the entire string. Therefore we can initiate a simple for loop.

Let’s have a look at the code:

Press + to interact
def isVowel(character): # function to check whether input character is a vowel
character = character.lower() # convert character to lower case so upper cases can also be handled
vowels = "aeiou" # string containing all vowels
if character in vowels: # check if given character is in vowels
return 1
else:
return 0
def countVowels(string): # function that returns the count of vowels
count = 0
for i in range(len(string)):
if isVowel(string[i]) : # check if character is vowel
count += 1
return count
# Driver code
string = "Educative"
print(countVowels(string))

In the code snippet above, the main function countVowels() takes a string as input. It traverses over the entire length of the string. The condition:

i in range(len(string))

makes sure that the for loop breaks if i becomes equal to the length of string, calculated by using len(string). Next, we use a condition:

isVowel(string[i])

to determine whether that particular character is a vowel or not. If this condition is satisfied we increment count by 11.

isVowel() is a function that returns TRUE if the character being passed is a vowel and FALSE otherwise.

Recursive Method

Let’s have a look at the recursive counterpart:

The code will therefore look something like this:

Press + to interact
def isVowel(character): # function to check whether input character is a vowel
character = character.lower() # convert character to lower case so upper cases can also be handled
vowels = "aeiou" # string containing all vowels
if character in vowels : # check if given character is in vowels
return 1
else:
return 0
def countVowels(string, n): # function that returns the count of vowels
# Base Case
if n == 1 :
return isVowel(string[0])
# Recursive Case
return countVowels(string, n - 1) + isVowel(string[n - 1])
# Driver code
string = "Educative"
print(countVowels(string, len(string)))

The isVowel() function for checking whether the character being input to it is a vowel or not remains the same. The major change that occurs is the conversion of the for loop to the recursive call.

Each time the length of the input string was being reduced in the iterative method. We are doing the same in the recursive method. We reduce the length of the input string and pass it another call of the same function. The leftover letter is checked whether it is a vowel or not and the result added in the function calls.


In the next lesson, we have a challenge for you to solve for yourself.