Open In App

Program to count the number of consonants in a word

Last Updated : 17 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Write a program to count the number of consonants in a given word. Consonants are the letters of the English alphabet excluding vowels (‘a’, ‘e’, ‘i’, ‘o’, ‘u’).

Examples:

Input: “programming”
Output: 8
Explanation: The eight consonants are: ‘p’, ‘r’, ‘g’, ‘r’, ‘m’, ‘m’, ‘n’, ‘g’)

Input: “hello”
Output: 3
Explanation: There are three consonants: ‘h’, ‘l’, ‘l’

Approach: To solve the problem, follow the below idea:

The problem can be solved by iterating through the entire word character by character and for each character, check if the character is a vowel. If the character is ‘a’ or ‘e’ or ‘i’ or ‘o’ or ‘u’, then it is a vowel otherwise it is a consonant. If the character is a consonant, increment the answer by 1.

Step-by-step algorithm:

  • Initialize a variable to store the count of consonants.
  • Iterate through each character in the word.
  • Check if the character is a consonant (not a vowel).
  • If it is a consonant, increment the count.
  • Print the final count.

Below is the implementation of the approach:

C++




#include <iostream>
 
using namespace std;
 
// function to check whether ch is a lowercase alphabet or
// not
bool isLowerCaseAlphabet(char ch)
{
    return ch >= 'a' && ch <= 'z';
}
 
// function to check whether ch is a lowercase vowel or not
bool isVowel(char ch)
{
    return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o'
           || ch == 'u';
}
 
int main()
{
 
    string word = "programming";
    int consonantCount = 0;
 
    for (int i = 0; i < word.length(); ++i) {
        // Convert to lowercase for case-insensitivity
        char ch = tolower(word[i]);
        if (isLowerCaseAlphabet(ch) && !isVowel(ch)) {
            consonantCount++;
        }
    }
 
    cout << "Number of consonants: " << consonantCount
         << endl;
 
    return 0;
}


C




#include <stdio.h>
 
// function to check whether ch is a lowercase alphabet or not
int isLowerCaseAlphabet(char ch)
{
    return (ch >= 'a' && ch <= 'z');
}
 
// function to check whether ch is a lowercase vowel or not
int isVowel(char ch)
{
    return (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o'
            || ch == 'u');
}
 
int main()
{
    char word[] = "programming";
    int consonantCount = 0;
 
    for (int i = 0; i < strlen(word); ++i) {
        // Convert to lowercase for case-insensitivity
        char ch = tolower(word[i]);
        if (isLowerCaseAlphabet(ch) && !isVowel(ch)) {
            consonantCount++;
        }
    }
 
    printf("Number of consonants: %d\n", consonantCount);
 
    return 0;
}


Java




public class ConsonantCounter {
    // function to check whether ch is a lowercase alphabet
    // or not
    static boolean isLowerCaseAlphabet(char ch)
    {
        return ch >= 'a' && ch <= 'z';
    }
 
    // function to check whether ch is a lowercase vowel or
    // not
    static boolean isVowel(char ch)
    {
        return ch == 'a' || ch == 'e' || ch == 'i'
            || ch == 'o' || ch == 'u';
    }
 
    public static void main(String[] args)
    {
        String word = "programming";
        int consonantCount = 0;
 
        for (int i = 0; i < word.length(); ++i) {
            // Convert to lowercase for case-insensitivity
            char ch = Character.toLowerCase(word.charAt(i));
            if (isLowerCaseAlphabet(ch) && !isVowel(ch)) {
                consonantCount++;
            }
        }
 
        System.out.println("Number of consonants: "
                           + consonantCount);
    }
}


Python3




def is_lower_case_alphabet(ch):
    return 'a' <= ch <= 'z'
 
def is_vowel(ch):
    return ch in {'a', 'e', 'i', 'o', 'u'}
 
word = "programming"
consonant_count = 0
 
for i in range(len(word)):
    # Convert to lowercase for case-insensitivity
    ch = word[i].lower()
    if is_lower_case_alphabet(ch) and not is_vowel(ch):
        consonant_count += 1
 
print("Number of consonants:", consonant_count)


C#




using System;
 
class Program {
    // Function to check whether ch is a lowercase alphabet
    // or not
    static bool IsLowerCaseAlphabet(char ch)
    {
        return ch >= 'a' && ch <= 'z';
    }
 
    // Function to check whether ch is a lowercase vowel or
    // not
    static bool IsVowel(char ch)
    {
        return ch == 'a' || ch == 'e' || ch == 'i'
            || ch == 'o' || ch == 'u';
    }
 
    static void Main()
    {
        string word = "programming";
        int consonantCount = 0;
 
        for (int i = 0; i < word.Length; ++i) {
            // Convert to lowercase for case-insensitivity
            char ch = char.ToLower(word[i]);
            if (IsLowerCaseAlphabet(ch) && !IsVowel(ch)) {
                consonantCount++;
            }
        }
 
        Console.WriteLine("Number of consonants: "
                          + consonantCount);
    }
}


Javascript




// Function to check whether ch is a lowercase alphabet or not
function isLowerCaseAlphabet(ch) {
    return ch >= 'a' && ch <= 'z';
}
 
// Function to check whether ch is a lowercase vowel or not
function isVowel(ch) {
    return ch === 'a' || ch === 'e' || ch === 'i' || ch === 'o' || ch === 'u';
}
 
let word = "programming";
let consonantCount = 0;
 
for (let i = 0; i < word.length; ++i) {
    // Convert to lowercase for case-insensitivity
    let ch = word[i].toLowerCase();
    if (isLowerCaseAlphabet(ch) && !isVowel(ch)) {
        consonantCount++;
    }
}
 
console.log("Number of consonants: " + consonantCount);


Output

Number of consonants: 8

Time Complexity: O(N) where N is the length of the word.
Auxiliary Space: O(1) (constant space is used)



Similar Reads

Program to count the number of characters in a word
Write a program to count the number of characters in a word. Examples: Input: Word: "programming"Output: 11 Input: Word: "hello"Output: 5 Approach: To solve the problem, follow the below idea: To count the number of characters in a word, maintain a variable to count all the characters. Iterate through each character in the word and increment the co
2 min read
Program to count the number of vowels in a word
Write a program to count the number of vowels in a given word. Vowels include 'a', 'e', 'i', 'o', and 'u' (both uppercase and lowercase). The program should output the count of vowels in the word. Examples: Input: "programming"Output: 3Explanation: The word "programming" has three vowels ('o', 'a', 'i'). Input: "HELLO"Output: 2Explanation: The word
3 min read
Program to reverse a word
Write a program to reverse a given word. Examples: Input: "Hello" Output: "olleH" Input: "Programming" Output: "gnimmargorP" Approach: To solve the problem, follow the below idea: It can be observed that we can reverse a word by traversing over the original string in reverse order and then pushing the characters from the back to a new string. Final
3 min read
Program to count the number of days between two years
Given two years. Write a program to count the number of days between the two years. Examples: Input: startYear = 1990, endYear = 2001Output: 4383 Explanation: Years 1992, 1996 and 2000 are leap year and all 9 others are non-leap years. So, total number of days are: 366 * 3 + 365 * 9 = 4383 Input: startYear = 1890, endYear = 1998Output: 39811 Approa
4 min read
Program to count the number of words in a sentence
Write a program to count the number of words in a given sentence. A word is defined as a sequence of characters separated by spaces. Examples: Input: "The quick brown fox"Output: 4Explanation: The sentence has four words - "The", "quick", "brown", "fox". Input: "The quick brown fox"Output: 4Explanation: The sentence has four words - "The", "quick",
3 min read
Program to count the number of months between given two years
Given a start year and end year. Write a program to count number of months between given two years (both inclusive). Examples: Input: startYear = 1991, endYear = 2023Output: 396Explanation: The number of years between 1991 and 2023 (both inclusive) are: 33. So, total number of months = 396. Input: startYear = 2010, endYear = 2023Output: 168Explanat
4 min read
Program to count number of days between two given months
Write a program to count the number of days between two given months (including start as well as end month). Assume the number of days in February as 28. Examples: Input: startMonth = "january", endMonth ="january"Output: 31Explanation: January has 31 days. Input: startMonth = "january", endMonth = "july"Output: 212Explanation: 31 + 28 + 31 + 30 +
6 min read
Hello World Program : First program while learning Programming
In this article, I'll show you how to create your first Hello World computer program in various languages. Along with the program, comments are provided to help you better understand the terms and keywords used in theLearning program. Programming can be simplified as follows: Write the program in a text editor and save it with the correct extension
6 min read
Program to generate a random single digit number
Write a program to generate a random single-digit number. Example 1: 7Example 2: 3 Approach: To solve the problem, follow the below idea: To generate a random single-digit number, we can first generate a random integer and then take apply modulo to get the last digit of that random integer. This last digit can be the random single digit number. Ste
2 min read
Program to generate a random two-digit number
Write a program to generate a random two-digit number. Example 1: 73Example 2: 26 Approach: To solve the problem, follow the below idea: We can generate a random two-digit number by generating a random integer first and then modulo it by 90. Now, after modulo 90 the remainder can be in the range 0 to 89, so in order to have the remainder as a two-d
2 min read
Article Tags :