Tutorialspoint
Problem
Solution
Submissions

Number of Vowels and Consonants in a String

Certification: Basic Level Accuracy: 28% Submissions: 25 Points: 10

Write a C++ program that counts the number of vowels and consonants in a string using pointers. The program should take a string as input and return the count of vowels and consonants.

Example 1
  • Input: string = "Hello"
  • Output: Vowels: 2, Consonants: 3
  • Explanation:
    • Step 1: Initialize vowel and consonant counters to 0.
    • Step 2: Initialize a pointer to the start of the string.
    • Step 3: Iterate through each character of the string using the pointer.
    • Step 4: For each character, check if it's a vowel (a, e, i, o, u, A, E, I, O, U) and increment the vowel counter if true.
    • Step 5: If the character is an alphabet and not a vowel, increment the consonant counter.
    • Step 6: Return the counts (vowels = 2, consonants = 3).
Example 2
  • Input: string = "C++"
  • Output: Vowels: 0, Consonants: 3
  • Explanation:
    • Step 1: Initialize vowel and consonant counters to 0.
    • Step 2: Initialize a pointer to the start of the string.
    • Step 3: Iterate through each character of the string using the pointer.
    • Step 4: For each character, check if it's a vowel (a, e, i, o, u, A, E, I, O, U) and increment the vowel counter if true.
    • Step 5: If the character is an alphabet and not a vowel, increment the consonant counter.
    • Step 6: Return the counts (vowels = 0, consonants = 3).
Constraints
  • 1 ≤ len(string) ≤ 10^3
  • String contains printable ASCII characters
  • Time Complexity: O(n) where n is the length of the string
  • Space Complexity: O(1)
StringsPointers and ReferencesWalmartSwiggy
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use pointers to traverse the string.
  • Check if each character is a vowel or consonant.
  • Maintain separate counters for vowels and consonants.

Steps to solve by this approach:

 Step 1: Define a function countVowelsAndConsonants that takes a constant character pointer and two integer references as parameters.

 Step 2: Initialize vowels and consonants counters to zero.
 Step 3: Iterate through each character of the string until the null terminator.
 Step 4: Convert each character to lowercase for consistent checking.
 Step 5: Check if the character is an alphabet letter (between 'a' and 'z').
 Step 6: If it's a vowel (a, e, i, o, u), increment the vowels counter; otherwise, increment the consonants counter.
 Step 7: In main, call countVowelsAndConsonants with a string and two integer variables.
 Step 8: Print the counts of vowels and consonants.

Submitted Code :