The for loop iterates through a collection, more specifically through anything that provides an iterator.
Syntax to use for loop in Kotlin.
In Kotlin, you can use for loop to iterate through following things
-
-
- Range
- Array
- String
- Collection
-
Example
The program will print numbers 1 through 10. During each step of the loop, the variable x will contain the value of the current element in the range.
Iterate through a String using For Loop
Without using index property
i
n
s
p
i
r
e
_
c
o
d
i
n
g
Iterate String Using Index property
i
n
s
p
i
r
e
_
c
o
d
i
n
g
Iterate String Using withIndex() Library Function
0th position: i
1th position: n
2th position: s
3th position: p
4th position: i
5th position: r
6th position: e
7th position: _
8th position: c
9th position: o
10th position: d
11th position: i
12th position: n
13th position: g
Different ways to iterate through Range
Here, we have range from 1 to 6 which is being traversed from first to last item using for loop in kotlin.
1
2
3
4
5
6
Here, we have range from 1 to 6. But, we are iterating the Range in reverse order i.e. from last item to first item.
6
5
4
3
2
1
Here, we have range from 1 to 6. We are iterating the Range from first item to last item in steps of 2.
1
3
5
Here, we have range from 1 to 6. But, we are iterating the Range in reverse order i.e. from last item to first item. Also, we are iterating in steps of 2.
6
4
2
Questions
I hope the description was understandable and clear. But if you have still questions, then leave me comments below! 😉
Have a nice a day! 🙂