Kotlin Program to Count Vowels and Consonants
when or if conditions, then incrementing vowel or consonant counters accordingly.Examples
How to Think About It
Algorithm
Code
fun main() {
val input = readLine() ?: ""
var vowels = 0
var consonants = 0
val vowelsSet = setOf('a', 'e', 'i', 'o', 'u')
for (char in input.lowercase()) {
if (char in 'a'..'z') {
if (char in vowelsSet) vowels++ else consonants++
}
}
println("Vowels: $vowels, Consonants: $consonants")
}Dry Run
Let's trace the input "Kotlin" through the code
Input reading
input = "Kotlin"
Initialize counters
vowels = 0, consonants = 0
Convert to lowercase and iterate
characters: 'k', 'o', 't', 'l', 'i', 'n'
Check each character
k: consonant, vowels=0, consonants=1 o: vowel, vowels=1, consonants=1 t: consonant, vowels=1, consonants=2 l: consonant, vowels=1, consonants=3 i: vowel, vowels=2, consonants=3 n: consonant, vowels=2, consonants=4
Print result
Vowels: 2, Consonants: 4
| Character | Is Letter? | Is Vowel? | Vowels Count | Consonants Count |
|---|---|---|---|---|
| k | Yes | No | 0 | 1 |
| o | Yes | Yes | 1 | 1 |
| t | Yes | No | 1 | 2 |
| l | Yes | No | 1 | 3 |
| i | Yes | Yes | 2 | 3 |
| n | Yes | No | 2 | 4 |
Why This Works
Step 1: Check each character
The program looks at each character to see if it is a letter between 'a' and 'z'. This filters out numbers and symbols.
Step 2: Identify vowels
It compares the character to a set of vowels. If it matches, the vowel count increases.
Step 3: Count consonants
If the character is a letter but not a vowel, it counts as a consonant.
Step 4: Output counts
Finally, the program prints how many vowels and consonants were found.
Alternative Approaches
fun main() {
val input = readLine() ?: ""
val vowels = Regex("[aeiouAEIOU]")
val consonants = Regex("[bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ]")
val vowelCount = vowels.findAll(input).count()
val consonantCount = consonants.findAll(input).count()
println("Vowels: $vowelCount, Consonants: $consonantCount")
}fun main() {
val input = readLine() ?: ""
val vowelsSet = setOf('a', 'e', 'i', 'o', 'u')
val lowerInput = input.lowercase()
val vowelCount = lowerInput.count { it in vowelsSet }
val consonantCount = lowerInput.count { it in 'a'..'z' && it !in vowelsSet }
println("Vowels: $vowelCount, Consonants: $consonantCount")
}Complexity: O(n) time, O(1) space
Time Complexity
The program checks each character once, so time grows linearly with input size.
Space Complexity
Only a few counters and a small set of vowels are stored, so space is constant.
Which Approach is Fastest?
The simple loop with set membership is fastest and uses least memory; regex is more expressive but slower.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Loop with set membership | O(n) | O(1) | Fast and memory efficient |
| Regex matching | O(n) | O(1) | Concise but slower for large input |
| Filter and count functions | O(n) | O(1) | Readable and idiomatic Kotlin |