Understanding of for loop in Kotlin with details.

Ansar Ali
2 min readFeb 15, 2021

--

For loop, We need to understand the for loop first.

For loop run through the iterator.

Iterator:- It means, An iterator is an object that can contain countable numbers. you can traverse through the values of numbers. like: collection, array, rang, etc.

Syntax of for loop…

for(item in Colliection){

// your desired code

}

In for loop, i is a variable that will contain the value of the iterator from time to time. When the loop will finish the value of the variable item will change every time.

Example…

fun main(args:Array<String>){
for(a in 1..3){
print(a)
}
}

Let’s understand it.

  • Call for loop in the main function of kotlin.
  • We have an iterator, In which has a range of 1 to 5.
  • And variable a, its value will be changed after finish a loop.
  • There is in operator, which will check the iterator value every time.
  • When for loop will execute the first time a variable has 1 as a value. then the loop will go in the body part of for loop. And we are using the print function which will print 1 first time. Value of variable a will 2 second time and in operator will check 2 is available or not in iterator if yes then it will go in the body part and print 2. The third time, the value of a will 3 and lastly will print 3. 4th time value of a will be 4, and again in operator will check the iterator but this time there is no 4 in the iterator. Execution will not go into the body part and the loop will finish here.

Result…

123

I hope it will help someone.

Thanks:)

--

--

Ansar Ali
Ansar Ali

Written by Ansar Ali

Flutter and Android app developer.

Responses (2)