while loops
Kotlin while
loops have the simplest syntax. Think back to the if
statements for a moment; we could use virtually any combination of operators and variables in the conditional expression of the if
statement. If the expression evaluated to true, then the code in the body of the if
block is executed. With the while
loop, we also use an expression that can evaluate to true or false:
var x = 10 while(x > 0) { Log.i("x=", "$x") x-- }
Take a look at the preceding code; what happens here is as follows:
Outside of the
while
loop, anInt
type namedx
is declared and initialized to 10.Then, the
while
loop begins; its condition isx > 0
. So, thewhile
loop will execute the code in its body.The code in its body will repeatedly execute until the condition evaluates to false.
So, the preceding code will execute 10 times.
On the first pass, x
equals 10 on the second pass it equals 9, then 8, and so on. But once x
is equal to 0, it is, of course, no longer greater than 0. At this point...