Sure! The while
loop in Kotlin is used to repeatedly execute a block of code as long as a condition is true. Here's a simple explanation with an example:
Example
while (condition) {
// Code to be executed repeatedly
}
Let's say we want to print numbers from 1 to 5 using a while
loop:
Example
fun main() {
var count = 1 // Initialize a variable
while (count <= 5) { // Condition: Repeat until count is less than or equal to 5
println("Count: $count") // Print the value of count
count++ // Increment count by 1
}
}
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
count
with the value 1
.while
loop checks the condition count <= 5
. If it's true
, the block of code inside the loop is executed.count
.count
by 1 using count++
.count <= 5
becomes false
(when count
is greater than 5
), at which point the program exits the loop and continues with the rest of the code.The while
loop is a fundamental control flow construct in Kotlin that allows you to repeat a block of code based on a condition. It's useful for scenarios where you need to iterate over a sequence of values or perform actions until a certain condition is met.