Coding for All
Lesson 20: While Loop
While Loop Loop for as long as a condition stays true.
1fun main() {
2 val flags = booleanArrayOf(true, true, false)
3 var index = 0
4 while (flags[index]) {
5 println("flags[$index] is true")
6 index++
7 }
8}
Terminal
$ kotlinc Main.kt -include-runtime -d Main.jar
$ java -jar Main.jar
flags[0] is true
flags[1] is true
Every line, explained
fun main() {
Every Kotlin program starts at the main function. When you run the program, Kotlin looks for fun main() and runs everything between its { and } from top to bottom.
val flags = booleanArrayOf(true, true, false)
A boolean array; the last item is false, and that is what will stop our loop.
var index = 0
var creates a variable whose value CAN change later. The Kotlin habit is: use val unless you know the value must change. With a while loop you create the counter yourself, before the loop. It changes, so it is a var.
while (flags[index]) {
A while loop repeats its block for as long as the condition in the round brackets is true. The condition is checked again before every trip around the loop. Here the condition is flags[index]: the loop keeps going while the current item is true, and stops the moment it reaches flags[2], which is false.
println("flags[$index] is true")
println(...) prints whatever is inside the round brackets to the terminal, then moves to a new line. All lowercase, and no semicolon at the end; Kotlin does not need them. Prints which position was true, dropping the number index into the text.
index++
index++ increases index by 1. It is a short way of writing index = index + 1 (you can also write index += 1). Without this line, index would stay 0 and the loop would never end!
}
This } closes the while loop.
}
This closing curly brace } ends the main function. In Kotlin every opening brace { must have a matching closing brace }.