In this tutorial, you shall learn about While loop statement in Kotlin, its syntax, and how to use While statement to execute a task repeatedly in a loop, with examples.
Kotlin While loop
While Loop statement is used to execute a block of code repeatedly based on a condition.
In this tutorial, we will learn the syntax of While Loop statement, and its usage with the help of example programs.
Syntax
The syntax of While Loop statement is
while (condition) {
statements
}
- while: Kotlin keyword.
- condition: a boolean expression, or something that evaluates to a boolean value.
- statements: one or more Kotlin statements. This can be empty as well, if necessary.
- () parenthesis enclose the condition, and {} curly braces enclose the while loop body.
Examples
1. Print numbers from 1 to N using While Loop
In this following program, we will use While Loop to print numbers from 1
to n
.
Main.kt
fun main() {
var n = 4
var i = 1
while(i <= n){
println(i)
i++
}
}
Output
1
2
3
4
2. While Loop with break statement
In this following example, we will use while loop to print numbers from 1 to infinity. We use break statement inside While Loop to break the loop after printing the number 4
.
Kotlin Program – example.kt
fun main() {
var i = 1
while(true){
println(i)
i++
if(i > 4)
break
}
}
Output
1
2
3
4
Further Reading
Conclusion
In this Kotlin Tutorial, we learned how to use while and do while loops in Kotlin.