For loop

For loop

⇒ For loop

 
  • The for loop iterates through anything that provides an iterator.
for (item in Collection) print(item)
  • The body can be block
for (item : Int in ints){ // ... }
  • To iterate over a range of numbers, use a range expression:
for(i in 1..3){ println(i) }
here (” .. “) is range operator that tell to start iterate from number before start range (number before .. ) and iterate till end iterator
Start ≤ .. ≤ End
for (i in 6 downTo 0 step 2) { println(i) }
Here for loop start iteration over higher number and insteated of incresing it is decresing by 2
  • downTo - used in for loop to iterate in decresing order
  • step - defualt is 1 , but you can set acording ,
  • if step n is given , step will skips n index and goes to next iteration then again skip next n iteration
  • If you want to iterate through an array or a list with an index, you can do it this way:
fun main() { val array = arrayOf("a", "b", "c") for (i in array.indices) { println(array[i]) } }
  • Alternatively, you can use the withIndex library function:
fun main() { val array = arrayOf("a", "b", "c") for((index, value) in array.withIndex()) { println("the element at $index is $value") } }