Kotlin For Loop With Examples



Just like while loop, we have a different looping syntax in Kotlin - For Loops. For loops are used to execute the statements a certain number of times. With Kotlin Range, for loop becomes more powerful. Let's look at some examples - 

for(i in 1..5)
{
  println("Hello CheezyCode")
}

Explanation - This loop will print Hello CheezyCode 5 times. 1..5 is a concept of range in Kotlin. This for loop will start from 1 and ends at 5. After every iteration, the value of i is incremented by 1. 


Using step in for Loop

You can increment the step count by using the step keyword followed by the number inside for loop i.e. This step value is used for incrementing the value of a counter variable. After every iteration, the value will be incremented by the step. Refer to the code snippet below - 

for(i in 1..5 step 2)
{
  println("Hello CheezyCode ${i}")
}
//Output - 
//Hello CheezyCode 1
//Hello CheezyCode 3
//Hello CheezyCode 5

Explanation - Here we have mentioned step value as 2 so this loop will run only 3 times. Starting from index 1, the value of  "i" will be incremented by 2. So "i" will have values  - 1, 3, 5.


Decrementing For Loop or Reverse For Loops

You can even write for loops that are decrementing or you can say that running a for loop in reverse. Starting from 5 and going down to 1. For this, Kotlin has downTo which is used inside for loop. Refer below snippet - 

for(i in 5 downTo 1)
{
  println("Hello CheezyCode ${i}")
}
//Output - 
//Hello CheezyCode 5
//Hello CheezyCode 4
//Hello CheezyCode 3
//Hello CheezyCode 2
//Hello CheezyCode 1
Explanation - Here we are using downTo - which will decrement the value by 1 after every iteration. Starting from 5, it will go down to 1. You can also provide the step value if you don't want to decrement it by 1.


NOTE - The main use for loop comes into the picture when we want to iterate through a set of elements i.e. collections like arrays, lists, etc. This loop becomes handy in those cases as the syntax for iterating through elements is very concise.

That's it for this article. For more articles on Kotlin Tutorials For Beginner Series - refer to this.

Happy Learning !! Cheers From CheezyCode.

Comments

Popular posts from this blog

Create Android Apps - Getting Started

Polymorphism in Kotlin With Example