While loop is used to iterate a block of code repeatedly as long as the given condition returns true. In this guide, we will learn how to use while loop with the help of examples.
A simple while loop in Kotlin
In the following example we are displaying the value from 10 to 5 using while loop. The important point to note here is the counter, which is variable num in the following example, for ascending loop the counter value should increase to meet the given condition and for the descending loop the counter value should decrease in every iteration just like we did in the following example.
/** * created by Chaitanya for Beginnersbook.com */ package beginnersbook fun main(args : Array<String>){ var num = 10 while(num>=5){ println("Loop: $num") num-- } }
Output:
Infinite While loop
If the condition specified in the while loop never returns false then the loop iterates infinitely and never stops such while loops are called infinite while loops. We should always avoid such situation while writing code. Lets see few examples of infinite while loop.
1. Since the condition is always true this will run infinitely.
while (true){ println("loop") }
2. In this while loop we are incrementing the counter num
, the counter initial value is 10 and we are increasing it on every iteration, which means the specified condition num>=5 will always remain true and the loop will never stop.
var num = 10 while(num>=5){ println("Loop: $num") num++ }
3. The following loop will is also an infinite loop because the condition will always remain true as we are decreasing the value of num which means the condition num<=10 will always be satisfied.
var num = 5 while(num<=10){ println("Loop: $num") num-- }
Leave a Reply