
For Loop in Kotlin
📌 For Loop in Kotlin
The for
loop in Kotlin is used to iterate over a range, collection, array, or any iterable object. It provides a clean and concise syntax for traversing data.
✅ 1. Syntax of For Loop
for (i in 1..5) { println("Number: $i")}
Output:
Number: 2Number: 3Number: 4Number: 5
1..5
includes both1
and5
.
📌 Example 2: Using until
(Exclusive Range)
for (i in 1 until 5) { println("Number: $i")}
Output:
Number: 2Number: 3Number: 4
until
excludes the last value (5
).
✅ 3. For Loop with Step
You can specify a step using the step
keyword to skip numbers.
📌 Example:
for (i in 1..10 step 2) { println("Step: $i")}
Output:
Step: 3Step: 5Step: 7Step: 9
step 2
increments by 2 each time.
✅ 4. For Loop in Reverse
You can iterate in reverse using the downTo
keyword.
📌 Example:
for (i in 10 downTo 1) { println("Countdown: $i")}
Output:
Countdown: 9Countdown: 8Countdown: 7Countdown: 6Countdown: 5Countdown: 4Countdown: 3Countdown: 2Countdown: 1
downTo
iterates in decreasing order.
✅ 5. For Loop with Arrays and Collections
You can iterate over arrays, lists, sets, or maps using for
.
📌 Example: Iterate Over an Array
val fruits = arrayOf("Apple", "Banana", "Cherry")for (fruit in fruits) { println(fruit)}
Output:
AppleBananaCherry
📌 Example: Iterate Over a List with Index
You can use withIndex()
to get both index and value.
for ((index, color) in colors.withIndex()) { println("Index: $index, Color: Index: 0, Color: RedIndex: 1, Color: GreenIndex: 2, Color: Blue
📌 Example: Iterate Over a Map
val users = mapOf("Alice" to 25, "Bob" to 30)for ((name, age) in users) { println("$name is $age years old")}
Output:
Alice is 25 years oldBob is 30 years old
✅ 6. Conclusion
Use
..
for inclusive ranges.Use
until
for exclusive ranges.Use
step
to increment values.Use
downTo
to iterate in reverse.Use
withIndex()
for index-value iteration.Use destructuring for maps using
(key, value)
.