Open In App

Count consonants in a string (Iterative and recursive methods)

Last Updated : 20 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string, count total number of consonants in it. A consonant is an English alphabet character that is not vowel (a, e, i, o and u). Examples of constants are b, c, d, f, and g.

Examples : 

Input : abc de
Output : 3
There are three consonants b, c and d.

Input : geeksforgeeks portal
Output : 12

 1. Iterative Method 

C++




// Iterative CPP program to count total number
// of consonants 
#include <iostream>
using namespace std;
  
// Function to check for consonant
bool isConsonant(char ch)
{
    // To handle lower case
    ch = toupper(ch);
  
    return !(ch == 'A' || ch == 'E' || 
            ch == 'I' || ch == 'O' || 
            ch == 'U') && ch >= 65 && ch <= 90;
}
  
int totalConsonants(string str)
{
    int count = 0;
    for (int i = 0; i < str.length(); i++) 
  
        // To check is character is Consonant
        if (isConsonant(str[i]))
            ++count;
    return count;
}
  
// Driver code
int main()
{
    string str = "abc de";
    cout << totalConsonants(str);
    return 0;
}


Java

Python3

C#

PHP

Javascript

Output

3

Time Complexity: O(n), where n is the length of the string
Auxiliary Space: O(1)

 2. Recursive Method 

C++




// Recursive CPP program to count total number
// of consonants 
#include <iostream>
using namespace std;
  
// Function to check for consonant
bool isConsonant(char ch)
{
    // To handle lower case
    ch = toupper(ch);
  
    return !(ch == 'A' || ch == 'E' || 
            ch == 'I' || ch == 'O' || 
            ch == 'U') && ch >= 65 && ch <= 90;
}
  
// to count total number of consonants from 
// 0 to n-1
int totalConsonants(string str, int n)
{
    if (n == 1)
        return isConsonant(str[0]);
  
    return totalConsonants(str, n - 1) + 
           isConsonant(str[n-1]);
}
  
// Driver code
int main()
{
    string str = "abc de";
    cout << totalConsonants(str, str.length());
    return 0;
}


Java

Python3

C#

Javascript

Output

3

Time Complexity: O(n), where n is the length of the string
Auxiliary Space: O(n), due to recursive call stacks.

Illustration of recursive method:
 



Next Article

Similar Reads