Iterate Elements Of Array in Kotlin With Examples

Given an array of elements in Kotlin. Write a program to iterate elements of array in Kotlin and print them.

We will traverse array using while loop or for loop in Kotlin.

1. Iterate Array Using while and for Loop

fun main() {

	val arr = intArrayOf(1,2,3,4,5)

	println("Elements in Array Using for Loop: ")
	// Traverse using for loop
	for(element in arr) {
		print(" $element")
	}
	println("")

	println("Elements in Array Using while Loop: ")
	// Traverse using while loop
	var index = 0
	while (index < arr.size) {
		print(" ${arr[index]}")
		index++
	}
	println("")
}

When you run the program, output will be –

Elements in Array Using for Loop:
1 2 3 4 5
Elements in Array Using while Loop:
1 2 3 4 5

Here, we just run a for loop. At each iteration, we get item at that position.
For example,
In first iteration, element at 1st position is accessed.
In second iteration, element at 2nd position is accessed.
and so on…

Similarly,

In while Loop,
variable index is used as position for which we want to access elements in array.
index starts with 0 and increased by 1 after value at that position is accessed and printed.

Similarly, you can iterate elements of array in Kotlin for other data types (e.g. float, double, boolean or any other data type).