Remember the infinite while loop? Well, there is also such a thing called the infinite for loop.
Kotlin's for loop has no update statement to get wrong, so here is the same idea written as a while loop with an update at the end:
var i = 0
while (i < 10) {
println(i)
i--
i++ // i++ from the loop update
}
This is what happens during this loop:
0. Creates and initializes a variable i = 0
1. First iteration:
a. Is i < 10 true? <=> Is 0 < 10 true? Yes.
b. Run the code inside {}:
1) println(i) => Output: 0
2) i-- => i becomes -1
c. i++ => i becomes 0 again
2. Second iteration:
a. Is i < 10 true? <=> Is 0 < 10 true? Yes.
b. Run the code inside {}:
1) println(i) => Output: 0
2) i-- => i becomes -1
c. i++ => i becomes 0 again
3. Third iteration:
a. Is i < 10 true? <=> Is 0 < 10 true? Yes.
b. Run the code inside {}:
1) println(i) => Output: 0
2) i-- => i becomes -1
c. i++ => i becomes 0 again
...
This program will never terminate as i will always have value 0 and thus the condition i < 10 will always be satisfied.
The program would basically print 0 forever never exiting the loop.
Assignment
Follow the Coding Tutorial and let's practice with infinite for loops!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. PRO is unlimited.
