Kotlin Program to Display Characters from A to Z using loop

Example 1: Display Uppercased A to Z

fun main(args: Array<String>) {
    var c: Char

    c = 'A'
    while (c <= 'Z') {
        print("$c ")
        ++c
    }
}

When you run the program, the output will be:

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 

Like Java, you can loop through A to Z using a for loop because they are stored as ASCII characters in Kotlin.

So, internally, you loop through 65 to 90 to print the English alphabets.

Here's the equivalent Java code: Java Program to Display English Alphabets

With a little modification you can display lowercased alphabets as shown in the example below.


Example 2: Display Lowercased a to z

fun main(args: Array<String>) {
    var c: Char

    c = 'a'
    while (c <= 'z') {
        print("$c ")
        ++c
    }
}

When you run the program, the output will be:

a b c d e f g h i j k l m n o p q r s t u v w x y z 

You simply replace 'A' with 'a' and 'Z' with 'z' to display the lowercased alphabets. In this case, interally you loop through 97 to 122.

Did you find this article helpful?