Defining the while loop

The construct of while is similar to an if statement. Both of these work with conditions before executing the code block within. See the following example. Here, an if statement was written with a simple print line statement:

if(i <= 3) {
println("Print $i")
}

while(i <= 3) {
println("Print $i")
}

Once you have replaced the if with the while statement, the while loop is ready to use. However, do not forget to increment the value of i, otherwise the while loop will execute forever:

fun main(args: Array<String>) {
println("While loop")
var i = 1
while (i <= 3) {
println("While $i")
i++
}
}

This loop will execute three times and it will increment the value of i by one on each iteration. On the fourth iteration, the value of i will be 4 and the controlling statement will become false.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.78.83