Repetition with while

Computers are excellent at performing repetitious tasks—so you don’t have to.

The most basic form of repetition uses the while keyword. This loops over the same block as long as a controlling Boolean expression continues to produce true:

while (Boolean-expression) { // Code to be repeated }

The Boolean expression is evaluated once at the beginning of the loop and again before each further iteration through the block.

// RepetitionWithWhile/WhileLoop.kt fun condition(i: Int) = i < 100 fun main(args: Array<String>) { var i = 0 while (condition(i)) { print(".") i += 10 // [1] } } /* Output: .......... */

In condition(), the comparison operator < produces a Boolean result, so the compiler infers Boolean as the result type for condition().

The conditional expression for the while says: “repeat the statements in the body as long as condition() returns true.”

i = i + 10

There’s a second way to use while, in conjunction with the do keyword:

do { // Code to be repeated } while (Boolean-expression)

Rewriting WhileLoop.kt to use a do-while produces:

// RepetitionWithWhile/DoWhileLoop.kt fun main(args: Array<String>) { var i = 0 do { print(".") i += 10 } while (condition(i)) } /* Output: .......... */

The sole difference between while and do-while is that the body of the do- while always executes at least once, even if the Boolean expression evaluates to false the first time. In a while, if the conditional is false the first time, then the body never executes. In practice, do-while is less common than while.

The short versions of assignment operators are available for all mathematical operations (+=, -=, *=, /=, %=). Here, we see -= and %= in use:

// RepetitionWithWhile/AssignmentOperators.kt fun main(args: Array<String>) { var n = 10 val d = 3 print(n) while (n > d) { n -= d print(" - $d") } println(" = $n") var m = 10 print(m) m %= d println(" % $d = $m") } /* Output: 10 - 3 - 3 - 3 = 1 10 % 3 = 1 */

We find the remainder of the integer division of two natural numbers by first using a while loop, then using the remainder operator.

Adding 1 and subtracting 1 from a number are so common that they have their own increment and decrement operators: ++ and --. You can replace i += 1 with i++:

// RepetitionWithWhile/IncrementOperator.kt fun main(args: Array<String>) { var i = 0 while (i < 4) { print(".") i++ } } /* Output: .... */

In practice, while loops are not used for iterating over a range of numbers. The for loop is used instead. This is covered in the next atom.



Previous          Next

©2018 Mindview LLC. All Rights Reserved.