VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-to-count-the-number-of-consonants-in-a-word/

⇱ Program to count the number of consonants in a word - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program to count the number of consonants in a word

Last Updated : 17 Jan, 2024

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:


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)

Comment
Article Tags:
Article Tags: