w3resource

Kotlin Program: Check vowel or consonant


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


Pre-Knowledge (Before you start!)

  • Basic Kotlin Syntax.
  • Kotlin Functions.
  • Variables in Kotlin.
  • Character Handling.
  • Conditional Statements.
  • Lists in Kotlin.
  • String Interpolation.
  • Printing Output.

Hints (Try before looking at the solution!)

  • Define the main() Function.
  • Declare a Character Variable.
  • Convert to Lowercase.
  • Check Against Vowels.
  • Display the Output.
  • Test with Different Characters.
  • Common Errors to Avoid:
    • Forgetting to convert to lowercase.
    • Misplacing logic in if-else statements.
    • Using incorrect comparison methods.

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.

Go to:


PREV : Check number divisibility by 7.
NEXT : Print the first 10 natural numbers.

Kotlin Editor:


Improve this sample solution and post your code through Disqus

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.