C# Program to Count Vowels and Consonants
"aeiou".Contains(char.ToLower(c)), counts vowels and consonants separately, and prints the totals.Examples
How to Think About It
Algorithm
Code
using System; class Program { static void Main() { Console.Write("Enter a string: "); string input = Console.ReadLine(); int vowels = 0, consonants = 0; foreach (char c in input) { if (char.IsLetter(c)) { char lower = char.ToLower(c); if ("aeiou".Contains(lower)) vowels++; else consonants++; } } Console.WriteLine($"Vowels: {vowels}, Consonants: {consonants}"); } }
Dry Run
Let's trace the input "hello" through the code
Input received
input = "hello"
Initialize counters
vowels = 0, consonants = 0
Check each character
h (letter, not vowel) -> consonants = 1 e (vowel) -> vowels = 1 l (consonant) -> consonants = 2 l (consonant) -> consonants = 3 o (vowel) -> vowels = 2
Print result
Vowels: 2, Consonants: 3
| Character | IsLetter | IsVowel | Vowels Count | Consonants Count |
|---|---|---|---|---|
| h | true | false | 0 | 1 |
| e | true | true | 1 | 1 |
| l | true | false | 1 | 2 |
| l | true | false | 1 | 3 |
| o | true | true | 2 | 3 |
Why This Works
Step 1: Check if character is a letter
We use char.IsLetter(c) to ignore digits and symbols, counting only alphabetic characters.
Step 2: Convert to lowercase
Converting to lowercase with char.ToLower(c) simplifies vowel checking by avoiding case mismatches.
Step 3: Count vowels and consonants
If the character is in "aeiou", increment vowel count; otherwise, increment consonant count.
Alternative Approaches
using System; using System.Linq; class Program { static void Main() { Console.Write("Enter a string: "); string input = Console.ReadLine(); int vowels = input.Count(c => "aeiouAEIOU".Contains(c)); int consonants = input.Count(c => char.IsLetter(c) && !"aeiouAEIOU".Contains(c)); Console.WriteLine($"Vowels: {vowels}, Consonants: {consonants}"); } }
using System; class Program { static void Main() { Console.Write("Enter a string: "); string input = Console.ReadLine(); int vowels = 0, consonants = 0; foreach (char c in input) { if (char.IsLetter(c)) { switch (char.ToLower(c)) { case 'a': case 'e': case 'i': case 'o': case 'u': vowels++; break; default: consonants++; break; } } } Console.WriteLine($"Vowels: {vowels}, Consonants: {consonants}"); } }
Complexity: O(n) time, O(1) space
Time Complexity
The program loops through each character once, so time grows linearly with input size.
Space Complexity
Only a few counters are used, so extra space is constant regardless of input size.
Which Approach is Fastest?
The basic loop is efficient and clear; LINQ is concise but may have slight overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Basic loop with Contains | O(n) | O(1) | Clarity and beginner-friendly |
| LINQ Count with lambda | O(n) | O(1) | Concise code, intermediate users |
| Switch statement | O(n) | O(1) | Explicit vowel checks, readability |