Kotlin Program to Check Vowel or Consonant
when with conditions like char.lowercaseChar() in listOf('a','e','i','o','u') to identify vowels and treat others as consonants.Examples
How to Think About It
Algorithm
Code
fun main() {
print("Enter a character: ")
val ch = readLine()?.firstOrNull() ?: return
if (!ch.isLetter()) {
println("$ch is not an alphabet")
} else {
when (ch.lowercaseChar()) {
'a', 'e', 'i', 'o', 'u' -> println("$ch is a vowel")
else -> println("$ch is a consonant")
}
}
}Dry Run
Let's trace input 'B' through the code
Read input
User inputs 'B', stored in variable ch = 'B'
Check if letter
'B'.isLetter() returns true
Convert to lowercase
'B'.lowercaseChar() is 'b'
Check vowel list
'b' is not in ('a','e','i','o','u')
Print result
Print 'B is a consonant'
| Step | Character | Is Letter? | Lowercase | Is Vowel? | Output |
|---|---|---|---|---|---|
| 1 | B | true | b | false | B is a consonant |
Why This Works
Step 1: Check if input is a letter
Using isLetter() ensures the program only processes alphabets, ignoring digits or symbols.
Step 2: Normalize case
Converting to lowercase with lowercaseChar() simplifies vowel checking by handling both uppercase and lowercase inputs uniformly.
Step 3: Use when for vowel check
The when expression matches the character against vowels and prints the correct result, making the code clear and concise.
Alternative Approaches
fun main() {
print("Enter a character: ")
val ch = readLine()?.firstOrNull() ?: return
if (!ch.isLetter()) {
println("$ch is not an alphabet")
} else {
val c = ch.lowercaseChar()
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
println("$ch is a vowel")
} else {
println("$ch is a consonant")
}
}
}fun main() {
val vowels = setOf('a', 'e', 'i', 'o', 'u')
print("Enter a character: ")
val ch = readLine()?.firstOrNull() ?: return
if (!ch.isLetter()) {
println("$ch is not an alphabet")
} else if (vowels.contains(ch.lowercaseChar())) {
println("$ch is a vowel")
} else {
println("$ch is a consonant")
}
}Complexity: O(1) time, O(1) space
Time Complexity
The program performs a fixed number of checks regardless of input size, so it runs in constant time O(1).
Space Complexity
Only a few variables and a small set of vowels are stored, so space usage is constant O(1).
Which Approach is Fastest?
All approaches run in constant time; using a set may be slightly more readable but has similar performance to when or if-else.
| Approach | Time | Space | Best For |
|---|---|---|---|
| when expression | O(1) | O(1) | Clear and concise code |
| if-else statements | O(1) | O(1) | Simple logic, easy to understand |
| Set membership check | O(1) | O(1) | Easy to modify vowel list |