Iterate Elements Of Array in Kotlin With Examples

Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners. Also, if you are interested in content writing, you can mail us at tutorialwing@gmail.com.

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).

Support Us

If you like Tutorialwing and would like to contribute, you can email an article on any educational topic at tutorialwing@gmail.com. We would love to publish your article. See your article on Tutorialwing and help others with your knowledge. Follow Facebook, LinkedIn, Google+, Twitter, Youtube for latest updates.
Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners