Loops allows you to repeat a set of instructions multiple times.
Loops allows you to repeat a set of instructions multiple times.
Syntax of For Loops
Loop using a collection
for ([temporary_name] in [collection_name]) {
Loop using a specific Range
for ( [temporary_name] in [start]..[end] ) {
Examples
Iterating through an array of integers.
Looping using a range
In the example, the loop will iterate 5 times and print 1, 2, 3, 4, and 5.
Loop using until and downTo
In the above examples - the first - starts from 1 and goes until 10. Each iteration, the counter will be increase by 2 every time because of [step 2]. It will start at 1, then 3, then 5, then 7, then 9.
Loop using Array length
In the example, the loop will iteration 5 times since indices returns the length of the array - (5).
While Loops
While Loops are a different form of loop in Kotlin. Unlike the For Loop which repeats a set of instructions for a specific range, while loops repeats a set of instructions until a specific condition is false. They are used when you do not know the amount of iterations to complete a specific task.
Syntax for While Loops
The 2 type of while loops shown is the regular while loop (first) and the do-while loop (second).
Examples for While Loops
The above example is a simple while loop that will keep on going while the playerIsAlive boolean is true. It will not stop until playerIsAlive is set to false.
For this do-while loop example, it demonstrates the difference between the normal while loop and itself. Even though the condition for when the loop will continue is when x is greater than 0, the loop will still execute the code in the curly brackets once since it checks the condition afterwards.