What are loops in Kotlin?
We use loops in Kotlin when we want to perform an action repetitively. Loops help make our code more organized and manageable.
Kotlin supports three types of loops:
- The
whileloop - The
do-whileloop - The
forloop
The while loop
The while loop executes a block of code repeatedly, as long as the specified condition is true. When the condition becomes false, the loop terminates.
If the condition is false at the start of the loop, it does not execute the code.
Syntax
while (condition) {// Body}
Syntax of thewhile loop
Example
In the following code widget, we see the use of the while loop in Kotlin:
fun main(args : Array<String>) {// Declaring a variablevar i: Int = 0// Using the while loopwhile (i < 5) {i++}// Printing i on the consoleprintln(i)}
do {// Body} while (condition);
Syntax of the do-while loop
fun main(args : Array<String>) {// Declaring a variablevar i: Int = 0// Using the do-while loopdo {i++} while (i < 5)// Printing i on the consoleprintln(i)}
for (item in collection) {// Body}
Syntax of the for loop
fun main(args : Array<String>) {// Declaring a collectionvar numbers = arrayOf<Int>(1, 2, 3, 4)// Using the for loopfor (num: Int in numbers) {// Printing num on the consoleprintln(num)}}