In this tutorial you will learn about the Kotlin for Loop and its application with practical example.
Kotlin for Loop
The for loop takes a collection of data(ranges, arrays, collections, or anything that provides an iterator) and iterate through the items one at a time in sequence.
Table Of Contents−
Syntax :-
1 2 3 |
for (item in collection) { // body of for loop } |
For Loop to Iterate Through an Array
Example :-
1 2 3 4 5 6 |
fun main(args: Array<String>) { var daysOfWeek = arrayOf("Sun","Mon","Tue","Wed","Thu","Fri","Sat") for(day in daysOfWeek){ println(day) } } |
Output :-
1 2 3 4 5 6 7 |
Sun Mon Tue Wed Thu Fri Sat |
The array can also iterated through array indices (index) of array.
Example:-
1 2 3 4 5 6 |
fun main(args: Array<String>) { var daysOfWeek = arrayOf("Sun","Mon","Tue","Wed","Thu","Fri","Sat") for(day in daysOfWeek.indices){ println("Day $day is :" + daysOfWeek[day]) } } |
Output:-
1 2 3 4 5 6 7 |
Day 0 is :Sun Day 1 is :Mon Day 2 is :Tue Day 3 is :Wed Day 4 is :Thu Day 5 is :Fri Day 6 is :Sat |
Alternatively, you can use the withIndex library function as following –
Example:-
1 2 3 4 5 6 |
fun main(args: Array<String>) { var daysOfWeek = arrayOf("Sun","Mon","Tue","Wed","Thu","Fri","Sat") for((index,value) in daysOfWeek.withIndex()){ println("Day $index is :$value") } } |
Output:-
1 2 3 4 5 6 7 |
Day 0 is :Sun Day 1 is :Mon Day 2 is :Tue Day 3 is :Wed Day 4 is :Thu Day 5 is :Fri Day 6 is :Sat |
For loop Iterate Through a Range
Example:-
1 2 3 4 5 |
fun main(args: Array<String>) { for (i in 1..5) { println(i) } } |
Output:-
1 2 3 4 5 |
1 2 3 4 5 |
Different Ways to Iterate Through a Range
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
fun main(args: Array<String>) { print("for (i in 1..5) print(i) = ") for (i in 1..5) print(i) println() print("for (i in 5..1) print(i) = ") for (i in 5..1) print(i) // prints nothing println() print("for (i in 5 downTo 1) print(i) = ") for (i in 5 downTo 1) print(i) println() print("for (i in 1..4 step 2) print(i) = ") for (i in 1..5 step 2) print(i) println() print("for (i in 4 downTo 1 step 2) print(i) = ") for (i in 5 downTo 1 step 2) print(i) } |
Output:-
1 2 3 4 5 |
for (i in 1..5) print(i) = 12345 for (i in 5..1) print(i) = for (i in 5 downTo 1) print(i) = 54321 for (i in 1..4 step 2) print(i) = 135 for (i in 4 downTo 1 step 2) print(i) = 531 |
For loop Iterate Through a String
Example:-
1 2 3 4 5 6 |
fun main(args: Array<String>) { var text_str= "W3ADDA" for (ltr in text_str) { println(ltr) } } |
Output:-
1 2 3 4 5 6 |
W 3 A D D A |