How do i check given alphabet is vowel or Consonant with kotlin

Last updated Jan 16, 2023

In this kotlin example we will learn, how to check given alphabet is Vowel or Consonant. We can write kotlin program in two ways to check the Vowel or consonant. Similarly we can also check given string starts with a Vowel or Consonant in Kotlin

  • Using If statement
  • Using when

 

Using If statement

Step 1: Ask user to enter text with one character

Step 2: Take char from user entered text. We will take the user input from the commandline by readLine(), it reads as string. So take first character from string with string index 0

Step 3: Now let's compare user input value with Vowel characters if any of condition true then user entered character is Vowel other wise it is Consonant.

 

import java.util.Scanner
fun main() {

    print("Enter character: ")
    var c = readLine()
    var ch=c?.lowercase()?.get(0)
    val vowelConsonant = if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') "vowel" else "consonant"

    println("$c is $vowelConsonant")
    
}

 

Output:

Enter character: Z
Z is consonant

 

Enter character: I
I is vowel

 

 

Using when statement

Now let's write above example using when statement

import java.util.Scanner
fun main() {

    print("Enter character: ")
    var c = readLine()
   when(c?.lowercase()?.get(0)) {
        'a', 'e', 'i', 'o', 'u' -> println("$c is a vowel")
        else -> println("$c is a consonant")
    }
}

 

Output:

Enter character: E
E is a vowel

 

Conclusion: In this kotlin example we learned how to check the given character is Vowel or consonant using If and when statement. Here we took user inputs using readLine() method.

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

531 Views