Loop Statements execute its Body multiple times (while condition is TRUE or while iterating through Elements)
● for…in Statement iterates through Sequence or Array Elements and executes its Body for each Element.
● while Statement executes its Body while condition is TRUE. Condition is checked at the beginning of Body
● do .. while Statement executes its Body while condition is TRUE. Condition is checked at the end of Body.
You can use
● break Jump Statement to exit Loop Statement
● continue Jump Statement to skip rest of the Body and continue with next iteration from the beginning of Body
for…in can be used to iterate through Elements of Sequence or Array.
Iterate through Sequence Elements
for (i in 1..5 ) { println(i) } // 1 2 3 4 5
for (i in 1..5 step 2) { println(i) } // 1 3 5
for (i in 6 downTo 0 step 2) { println(i) } // 6 4 2 0
Iterate through Array Elements
val people = arrayOf("John", "Lucy", "Bob") // DECLARE ARRAY
for (person in people ) { println(person) } // John Lucy Bob
for (index in people.indices ) { println(people[index]) } // John Lucy Bob
for ((index, value) in people.withIndex()) { println("$index = $value") } // 0 = John, 1 = Lucy, 2 = Bob