While Loop in Kotlin With Examples

 

While Loop in Kotlin

In this post, we will know about while loop in Kotlin. Kotlin while loop is used to iterate the given array or list. In the case of the while loop, we use conditions.

The conditions are used to end the loop. After the specified amount of iteration. The iteration limit set by the programmer. The while loop is like for loop in Kotlin.


But while loop in Kotlin having its own importance. If we want to run the loop until the user wants to run the loop. In that case, while loop in Kotlin is very helpful.

Syntax of While Loop in Kotlin

while( Condition) {
//statements
//statements
}

Example of While Loop in Kotlin

In this example, we will know. How to print the first ten natural numbers using while loop in kotlin. You think there is no need to used while loop in Kotlin. We can write the first ten natural numbers.

But if someone wants you to print the first thousand natural numbers. On that case, it is very difficult to write thousand natural numbers . To solve this problem. We have to use a while loop in Kotlin.

While Loop in Kotlin

Output

While Loop in Kotlin

#Print first ten natural number using while loop in Kotlin

fun main() {

var i = 10

while(i > 0){

println(i)

i--
}

}

Output

While Loop in Kotlin

Mistake in While loop in Kotlin

If you are a programmer. Then you already know about an infinite loop. The infinite loop never terminates. The infinite loop runs an infinite amount of time.

Now question strikes your mind. When these loops run infinite time. In the previous example, you have seen a condition i++.

You know this condition is very helpful to end the loop. I forgot to write this condition i++. Then your programs enter an infinite stage and run infinite times.

Example

fun main() {

var i = 10

while(i > 0){

println(i)

}

}

Output

It runs infinite times.

Do while Loop in Kotlin

Do while loop is like while loop. While loop checks conditions first. If the condition is true, then only while block executes.

But do while loop executes first. Then it checks the condition. The do-while loop runs at once time. If the condition is not true also.

Example
#Print First then natural numbers using do-while loop in kotlin

fun main() {

var i = 1

do{
println(i)
i++
}
while(i < 11)

}

Output


1
2
3
4
5
6
7
8
9
10

Post a Comment