Loops in Kotlin

By | April 26, 2020

In this tutorial, we will learn about Loops in Kotlin. Loops are used to run a piece of code several times. For example, you want to show 1 to 100 numbers on screen it means you have to write println statement 100 times. But with the help of loop, you can do this by just writing println statement once.

Types of Loops in Kotlin:

  • for (as foreach loop)
  • for (as ordinary for loop)
  • while loop

For loop(as foreach loop):

The for loop is quite a famous loop and in Kotlin for loop can be used as foreach loop to fetch values from a range, collection etc.

Example Program(with an array):

fun main(args : Array<String>) {  
    val numbers = arrayOf(10,20,25,30,40)  
    for(num in numbers){  
        println(num)  
    }  
} 

Example Program(with a List):

fun main(args : Array<String>) {  
  val names = listOf("Raj", "Sonu", "Om")
   for (name in names) {
     println(name)
   } 
}

for (as ordinary for loop)

In this kind of loop, we can control the step size(increment or decrement). In this kind of loop we mention three things first one is the initial value, the second one is until or downTo, the third one is a step size. Check this following example.

Example Program:

fun main(args : Array<String>) {  
  for (x in 1 until 10 step 1) 
    println(x)
    
  println("\nDownTo Example")
  for (x in 10 downTo 0 step 1) 
    println(x)
}

While loop:

While loop in Kotlin is similar to while loop of Java. It takes a condition in it and iterates the body of loop until it found false condition.

fun main(args : Array<String>) {  
  var num = 0
   while (num < 10) {
    println(num)
    num++ 
    }
}