Kotlin Loops: Controlling Program Repetition
Loops are fundamental control flow structures in programming, enabling the repetition of code blocks until a specific condition is met. They are used for iterating through data collections, performing repetitive tasks, and controlling program flow based on conditions. Kotlin provides two primary types of loops: while loops and do...while loops.
While Loop: Repeated Execution Based on Condition
The while loop executes a block of code repeatedly as long as a specified condition remains true. It checks the condition before entering the loop, and if the condition is true, the loop body is executed. The loop continues to iterate until the condition becomes false.
Syntax of the While Loop:
while (condition) {
// Code to execute repeatedly
}
Example of a While Loop:
Consider printing numbers from 1 to 10:
var counter = 1
while (counter <= 10) {
println(counter)
counter++
}
In this example, the while loop checks the condition counter <= 10 before entering the loop. As long as the condition is true, the loop body is executed, printing the current value of counter and incrementing it by 1. The loop continues until counter reaches 11, making the condition false and terminating the loop.
Do...While Loop: Guaranteed Execution at Least Once
The do...while loop executes a block of code at least once before checking a condition. The loop body is executed first, and then the condition is evaluated. If the condition is true, the loop body is executed again, and the process continues until the condition becomes false.
Syntax of the Do...While Loop:
do {
// Code to execute at least once
} while (condition)
Example of a Do...While Loop:
Consider obtaining a user's input until they enter a valid number:
var input: Int?
do {
print("Enter a valid number: ")
input = readLine()?.toIntOrNull()
} while (input == null || input < 0)
println("You entered: $input")
In this example, the do...while loop executes the code block first, prompting the user for input and assigning it to the input variable. Then, the condition input == null || input < 0 is checked. If the condition is true, indicating invalid input, the loop body is executed again, prompting the user again. The loop continues until the user enters a valid number, making the condition false and terminating the loop.
Conclusion
While loops and do...while loops are essential tools for controlling program repetition in Kotlin. They enable programmers to iterate through data, perform repetitive tasks, and control program flow based on conditions. Understanding and effectively utilizing these loop constructs is crucial for writing efficient and well-structured Kotlin code.