ELEVATE YOUR BUSINESS WITH

Limitless customization options & Elementor compatibility let anyone create a beautiful website with Valiance.

For Loop in Kotlin

SELECT * FROM `itio_tutorial_master` WHERE `tutorial_menu`='25' AND `tutorial_submenu`='83' AND `tutorial_status`=1 LIMIT 1

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

kotlin

for (i in 1..5) { println("Number: $i")}

Output:

javascript

Number: 2Number: 3Number: 4Number: 5

  • 1..5 includes both 1 and 5.


📌 Example 2: Using until (Exclusive Range)

kotlin

for (i in 1 until 5) { println("Number: $i")}

Output:

javascript

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:

kotlin

for (i in 1..10 step 2) { println("Step: $i")}

Output:

makefile

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:

kotlin

for (i in 10 downTo 1) { println("Countdown: $i")}

Output:

makefile

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

kotlin

val fruits = arrayOf("Apple", "Banana", "Cherry")for (fruit in fruits) { println(fruit)}

Output:

nginx

AppleBananaCherry


📌 Example: Iterate Over a List with Index

You can use withIndex() to get both index and value.

kotlival colors = listOf("Red", "Green", "Blue")

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

kotlin

val users = mapOf("Alice" to 25, "Bob" to 30)for ((name, age) in users) { println("$name is $age years old")}

Output:

pgsql

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).

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql