w3resource

Kotlin Program: Check vowel or consonant

Kotlin Control Flow: Exercise-3 with Solution

Write a Kotlin program to check if a given character is a vowel or a consonant.

Sample Solution:

Kotlin Code:

fun main() {
    val input = 'A'
    //val input = 'e'
    //val input = 'p'

    val character = input.lowercaseChar()

    if (character in listOf('a', 'e', 'i', 'o', 'u')) 
       {
        println("The character '$input' is a vowel.")
       } 
    else 
      {
        println("The character '$input' is a consonant.")
      }
}

Sample Output:

Example output when input = "A":
The character 'A' is a vowel.
Example output when input = "e":
The character 'e' is a vowel.
Example output when input = "p":
The character 'p' is a consonant.

Explanation:

In the above exercise -

  • The main() function serves as the program's entry point.
  • The input variable is declared and assigned a character value.
  • The character variable is declared and assigned the lowercase version of the input character using the lowercaseChar() function. This function converts the character to its lowercase equivalent.
  • The code then uses an if-else statement to check whether the character is present in the vowels list. The list of vowels is defined as listOf('a', 'e', 'i', 'o', 'u').
  • If the character is found in the list of vowels, the code prints a message indicating that the character is a vowel using the println() function.
  • If the character is not found in the list of vowels, the code prints a message indicating that the character is a consonant using the println() function.

Kotlin Editor:


Previous: Check number divisibility by 7.
Next: Print the first 10 natural numbers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.