Kotlin Program to Check Whether an Alphabet is Vowel or Consonant

Determining whether a given alphabet is a vowel or a consonant is a fundamental task in programming, especially in text processing applications. Kotlin provides various ways to check for vowels and consonants efficiently. In this article, we’ll explore three Kotlin Program to Check Whether an Alphabet is Vowel or Consonant using different solutions and showcase their outputs.

1. Using when Expression

This example demonstrates how to check whether an alphabet is a vowel or consonant using Kotlin’s when expression. We use a when block to match the alphabet and determine whether it’s a vowel or consonant.

Code

Kotlin
fun main() {
    val alphabet = 'a'

    val result = when (alphabet.toLowerCase()) {
        'a', 'e', 'i', 'o', 'u' -> "Vowel"
        else -> "Consonant"
    }

    println("The alphabet '$alphabet' is a $result.")
}

Output

Kotlin
The alphabet 'a' is a Vowel.

2. Using if-else Statement

In this example, we use an if-else statement to check whether an alphabet is a vowel or consonant. We compare the alphabet with a list of vowels to determine the result.

Code

Kotlin
fun main() {
    val alphabet = 'b'

    val result = if (alphabet.toLowerCase() in listOf('a', 'e', 'i', 'o', 'u')) {
        "Vowel"
    } else {
        "Consonant"
    }

    println("The alphabet '$alphabet' is a $result.")
}

Output

Kotlin
The alphabet 'b' is a Consonant.

3. Using CharArray and Contains

Here, we convert the alphabet to a CharArray and use the contains function to check if it’s present in a list of vowels. This approach provides a concise way to check for vowels and consonants.

Code

Kotlin
fun main() {
    val alphabet = 'c'
    val vowels = charArrayOf('a', 'e', 'i', 'o', 'u')

    val result = if (vowels.contains(alphabet.toLowerCase())) {
        "Vowel"
    } else {
        "Consonant"
    }

    println("The alphabet '$alphabet' is a $result.")
}

Output

Kotlin
The alphabet 'c' is a Consonant.

4. Conclusion

Checking whether an alphabet is a vowel or consonant is a common text processing task, and Kotlin offers multiple ways to accomplish this efficiently. Whether using a when expression, an if-else statement, or CharArray operations, understanding these solutions enhances your Kotlin programming skills and prepares you for handling text-based operations effectively in your applications. Each example presented here provides a unique insight into Kotlin’s versatility in solving text processing problems, giving you the flexibility to choose the most suitable approach based on your specific requirements.