There is a more powerful way to use the for loop in Kotlin.
A Kotlin for loop goes through a range of values. Its loop variable takes each value of the range in turn. The general form is:
for (i in start until end) {
instruction1
instruction2
...
}
Let's break down each component:
The
startvalue is where the loop variable begins. The variable is created by the loop itself, so there is novaror type in front of it.The
endvalue is where the loop stops. Withuntilthe end value itself is not included, so the loop continues while the variable is less thanend.After each iteration the loop variable moves on to the next value in the range, by 1 unless you add
step. You never update it yourself.
Example:
for (i in 0 until 4) {
println("Hello world!")
}
// This code prints "Hello world!" on four different lines
Let's break down this code:
The start value is
0. The loop creates the iterator variableiand starts counting from 0.The end value is
4, which is excluded because we useuntil, meaning the loop will run as long as the iterator variable,i, is less than 4.After each iteration, after running the code inside
{},imoves on to the next value, which is 1 more.
This is what the computer does behind the scenes during this loop:
0. Creates and initializes a variable i = 0
1. First iteration:
a. Is i < 4 true? <=> Is 0 < 4 true? Yes.
b. Run the code inside {}. Print "Hello world!".
c. next value => i = 1
2. Second iteration:
a. Is i < 4 true? <=> Is 1 < 4 true? Yes.
b. Run the code inside {}. Print "Hello world!".
c. next value => i = 2
3. Third iteration:
a. Is i < 4 true? <=> Is 2 < 4 true? Yes.
b. Run the code inside {}. Print "Hello world!".
c. next value => i = 3
4. Fourth iteration:
a. Is i < 4 true? <=> Is 3 < 4 true? Yes.
b. Run the code inside {}. Print "Hello world!".
c. next value => i = 4
5. Fifth iteration:
a. Is i < 4 true? <=> Is 4 < 4 true? No.
b. Exit the loop.
Assignment
Let's print "I promise to learn coding." 5 times using a for loop.
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. PRO is unlimited.
