Kotlin – Iterate over Character Range

Iterate over a Range of Characters in Kotlin

To iterate over a range of characters in Kotlin, you can use For loop statement.

The syntax to iterate over a character range [‘a’, ‘d’] is

for (element in 'a'..'d') {
  //your code
}

Examples

In the following examples, you will learn how to iterate over a range of characters using For loop.

1. Iterate over the range ‘a’..’d’

In the following program, we take a character range 'a'..'d', and print each of the element to output in a For loop.

Kotlin Program

fun main() {
    for (ch in 'a'..'d') {
        println(ch)
    }
}

Output

a
b
c
d

2. Print all uppercase English alphabets using Range and For loop

In the following program, we define character range such that it contains all uppercase English alphabets, and iterate over the range using a For loop.

Kotlin Program

fun main() {
    for (ch in 'A'..'Z') {
        println(ch)
    }
}

Output

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