Write a Kotlin Program to Count the Number of Vowels and Consonants in a Sentence

In Kotlin, we can easily count the number of vowels and consonants in a sentence by iterating over each character in the sentence and checking if it is a vowel or a consonant.

Here is a Kotlin program that takes a sentence as input from the user and counts the number of vowels and consonants in the sentence:

fun main() {
    print("Enter a sentence: ")
    val sentence = readLine()?.toLowerCase()

    var vowels = 0
    var consonants = 0

    sentence?.forEach {
        when (it) {
            'a', 'e', 'i', 'o', 'u' -> vowels++
            in 'a'..'z' -> consonants++
        }
    }

    println("Number of vowels: $vowels")
    println("Number of consonants: $consonants")
}

In this program, we first prompt the user to enter a sentence using print(“Enter a sentence: “).

We then read the input sentence from the user using readLine() and convert it to lowercase using toLowerCase().

We then declare two variables, vowels and consonants, to keep track of the number of vowels and consonants in the sentence.

Next, we use the forEach method to iterate over each character in the sentence.

For each character, we check if it is a vowel using a when statement. If the character is a vowel, we increment the vowels variable.

If the character is a consonant, we check if it is a valid English alphabet using the range in ‘a’..’z’. If it is a valid alphabet, we increment the consonants variable.

Finally, we print the number of vowels and consonants in the sentence using println(“Number of vowels: $vowels”) and println(“Number of consonants: $consonants”).

This program is a simple and efficient way to count the number of vowels and consonants in a sentence using Kotlin.