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
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
Comments
Post a Comment
Hey there, liked our post. Let us know.
Please don't put promotional links. It doesn't look nice :)