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


In this article, we will understand how to count the vowels and consonants in Kotlin. Alphabets that include the following are called Vowels −

‘a’ ‘e’ ‘i’ ‘o’ ‘u’

All other alphabets are called Consonants.

Suppose our input is −

Hello, my name is Charlie

The desired output would be −

The number of vowels in the statement is: 8
The number of vowels in the Consonants is: 12

Algorithm

  • Step 1 − Start

  • Step 2 − Declare two integers: vowelsCount, consonantsCount and a string input

  • Step 3 − Define the values

  • Step 4 − Run a for-loop, check each letter whether it is a consonant or a vowel. Increment the respective integer. Store the value.

  • Step 5 − Display the result

  • Step 6 − Stop

Example 1

In this example, we will count the Number of Vowels and Consonants in a Sentence using a for loop. First, declare and set the input string

var myInput = "Hello, my name is Charlie"

Now, set the variables for vowels and consonants and initialize to zero

var vowelsCount = 0
var consonantsCount = 0

Count the vowels and consonants

myInput = myInput.toLowerCase() for (i in 0..myInput.length - 1) { val ch = myInput[i] if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') { ++vowelsCount } else if (ch in 'a'..'z') { ++consonantsCount } }

Let us now see the complete example to count the number of vowels and consonants using a for loop

fun main() { var myInput = "Hello, my name is Charlie" var vowelsCount = 0 var consonantsCount = 0 println("The statement is defined as: $myInput ") myInput = myInput.toLowerCase() for (i in 0..myInput.length - 1) { val ch = myInput[i] if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') { ++vowelsCount } else if (ch in 'a'..'z') { ++consonantsCount } } println("The vowel count is: $vowelsCount") println("The consonants count is: $consonantsCount") }

Output

The statement is defined as: Hello, my name is Charlie
The vowel count is: 8
The consonants count is: 12

Example 2

In this example, we will to count the Number of Vowels and Consonants in a Sentence −

fun main() { var myInput = "Hello, my name is Charlie" println("The statement is defined as: $myInput ") count(myInput) } fun count(input: String) { var myInput = input var vowelsCount = 0 var consonantsCount = 0 myInput = myInput.toLowerCase() for (i in 0..myInput.length - 1) { val ch = myInput[i] if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') { ++vowelsCount } else if (ch in 'a'..'z') { ++consonantsCount } } println("The vowel count is: $vowelsCount") println("The consonants count is: $consonantsCount") }

Output

The statement is defined as: Hello, my name is Charlie
The vowel count is: 8
The consonants count is: 12

Updated on: 13-Oct-2022

645 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements