Left Index

Kotlin Loop

The for loop in Kotlin iterates through anything that provides an iterator. It iterates through arrays, ranges, collections, or anything that provides for iterate. Kotlin for loop is equivalent to the foreach loop in languages like C# or java.


Syntax of for loop in Kotlin:

Syntax:
for(item in Collection) {
	// body for loop
}

Let's have an example of loop with array:

Example:
package com.theitbulls.kotlinex

fun main(args: Array<String>) {
	var numArr = arrayOf(29, 21, 13, 43)

	for(item in numArr) {
		println(item)
	}
}

Output:
29
21
13
43

Note: The elements of an array are iterated on the basis of indices (i..e index) of array, and we can get index of current array, For example:

Example:
package com.theitbulls.kotlinex

fun main(args: Array<String>) {
	var numArr = arrayOf(29, 21, 13, 43)

	for(item in numArr.indices) {
		println("Value of numArr[${item}]: ${numArr[item]}")
	}
}

Output:
Value of numArr[0]: 29
Value of numArr[1]: 21
Value of numArr[2]: 13
Value of numArr[3]: 43

Iterate Through a Range: In below Kotlin example, the loop iterates through the range and prints individual item

Example:
package com.theitbulls.kotlinex

fun main(args: Array<String>) {
	// print nothing, because range order is reverse
	for(item in 5..1) {
		print("${item}, ")
	}
	println()
	
	// if you want to print reverse value use downTo
	for(item in 5 downTo 1) {
		print("${item}, ")
	}
	println()
	
	// print values from 1 to 5 
	for(item in 1..5) {
		print("${item}, ")
	}
	println()
	
	// print values from 5 to 2, start with 5 and end with 2
	for(item in 5 downTo 2) {
		print("${item}, ")
	}
	println()

	// print values from 10 - 2 with every 2nd step
	for(item in 10 downTo 2 step 2) {
		print("${item}, ")
	}
	println()
}

Output:
5, 4, 3, 2, 1, 
1, 2, 3, 4, 5, 
5, 4, 3, 2, 
10, 8, 6, 4, 2,