Twitter LogoFacebook Logo
For and While Loops
[object Object]
By: King

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] ) {


}

for ( [temporary_name] in [start] downTo [end] step [amount_to_increment]) {

}

for ( [temporary_name] in [collection_name].indices() ) {

}

Examples

Iterating through an array of integers.

val lotteryNumbers = arrayOf<Int>(32, 6, 20, 1, 7);

for(number in lotteryNumbers) {
     println(number)
}

Looping using a range

for(number in 1..5) {
    println(number)
}

In the example, the loop will iterate 5 times and print 1, 2, 3, 4, and 5.

Loop using until and downTo

for(number in 1 until 10 step 2) {
            
}

for(number in 10 downTo 0 step 2) {
            
}

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.


If step were 3, the counter will be increased by 3 after each iteration.

In the second example above, it is the opposite. It starts from 10 and goes down to 0 with a step of 2. 10 > 8 > 6 > 4 > 2 > 0.

Loop using Array length

val lotteryNumbers = arrayOf<Int>(32, 6, 20, 1, 7)

for(number in lotteryNumbers.indices) {
        
}

In the example, the loop will iteration 5 times since indices returns the length of the array - (5).


The value of number will be 0, 1, 2, 3, and 4.

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

while ([condition]) {
    ...
}

do {
    ...
} while ([condition]) 

The 2 type of while loops shown is the regular while loop (first) and the do-while loop (second).


The difference between the two is that the do-while loop will execute the instructions in the curly brackets - { } - at least once before checking if the condition is true/false.

Examples for While Loops

var playerIsAlive = true;

while(playerIsAlive) {
      // Code to repeat here
}

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.

var x = 0;

do {
      println("Executed!")
} while (x > 0)

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.


Sign In