There are several ways to repeat a block of code while a certain condition is true. In this topic, we will learn how to do it with two loops: while and do...while. The difference between them is the repetition order and the evaluation of the condition.
While loop
The while loop includes a block of code and a condition, which is a boolean expression. If the condition is true, the loop initiates the statements. They are repeated until the condition becomes false. This loop checks the condition before the execution, so it is also known as a pre-test loop. Take a look at the example:
while (condition) {
// body: do something repetitive
}
The loop body can contain any kind of statement: declaring variables, reading data from the standard input, conditional expressions, and even nested loops.
You can also write an infinite loop if the condition remains true:
while (true) {
// body: do something indefinitely
}
We will take a closer look at infinite loops later.
For now, consider the example below. The program uses a while loop to print integer numbers only when the variable is less than 5.
fun main() {
var i = 0
while (i < 5) {
println(i)
i++
}
println("Completed")
}
Let us explain the work behind this loop. First, 0 is assigned to the mutable variable i. Before the first execution of the loop, the program checks whether the expression i < 5 is true. As i is 0, the loop is activated. The loop body has two statements: first, it displays the current value of i and second, it increments it by 1. After this, the expression i < 5 is evaluated again. The i becomes 1; it is also true, so the process repeats. It keeps happening until i becomes 5. i < 5 becomes false, so the execution of this loop terminates. The program proceeds to the next statement and prints Completed. This is the output of the loop:
0
1
2
3
4
Completed
Loops can be used to process characters, strings, and any other data types. The program below displays English letters in a single line.
fun main() {
var letter = 'A'
while (letter <= 'Z') {
print(letter)
letter++
}
}
The program takes the first letter A and then executes the loop until the letter becomes Z. The program also prints the current character and goes on to the next one. So the output is:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
It is possible to get the next character (according to the Unicode table) using the increment operator.
Our third example contains a program that reads any number of words from the standard input and then prints them. It uses the hasNext function of Scanner to check whether the input has a value.
import java.util.*
fun main() {
val scanner = Scanner(System.`in`)
while (scanner.hasNext()) {
val next = scanner.next()
println(next)
}
}
Input:
Kotlin is a modern language
Output:
Kotlin
is
a
modern
language
Use scanner.hasNext() for strings and scanner.hasNextInt() for integers when you do not know the size of your input data. Note that you can stop input in the console in IDEA by pressing Ctrl+D.
Do...while loop
A do...while loop is executed first, after that the program tests a condition. If the condition is true, it repeats the loop until the condition becomes false. Since do...while loops check the condition after execution, the loop is also known as a post-test loop. In contrast with the while loop, which tests the condition before the execution, the do..while loop is an exit-condition loop. So, the body is always executed at least once.
This loop contains three parts: the do keyword, a body, and while(condition):
do {
// body: do something
} while (condition)
The program below reads an integer number from the standard input and displays the number. If a user enters 0, the program prints it and then stops. The example below shows the work of the loop:
fun main() {
do {
val n = readln().toInt()
println(n)
} while (n > 0)
}
You can set a variable in the loop body and then use it in the condition.
Input:
1
2
4
0
Output:
1
2
4
0
The do...while loop can also be infinite just like the while loop.
Conclusion
In this topic, we have covered two basic but very useful loops: while and do...while. They both have a body and a condition, the only difference being the order of their execution. A while loop checks a condition before the body execution, a do...while loop checks it after the first execution.
In practice, programmers do not use do..while as often as while. A good example of using this loop is a program that reads data from the standard input until a user enters a certain number or a string. Now you know the basics of these loops. Let's practice!