0
0
Kotlinprogramming~5 mins

For loop over collections in Kotlin

Choose your learning style9 modes available
Introduction

A for loop helps you repeat actions for each item in a list or collection. It makes working with groups of things easy and organized.

When you want to print each name in a list of friends.
When you need to add up all numbers in a collection.
When you want to check each item in a shopping cart.
When you want to change or use every element in a list one by one.
Syntax
Kotlin
for (item in collection) {
    // do something with item
}

item is a temporary name for each element as you loop.

collection can be a list, set, or any group of items.

Examples
This prints each fruit name from the list.
Kotlin
val fruits = listOf("apple", "banana", "cherry")
for (fruit in fruits) {
    println(fruit)
}
This prints each number doubled.
Kotlin
val numbers = listOf(1, 2, 3, 4)
for (num in numbers) {
    println(num * 2)
}
This prints each character in uppercase.
Kotlin
val chars = setOf('a', 'b', 'c')
for (ch in chars) {
    println(ch.uppercaseChar())
}
Sample Program

This program goes through each animal in the list and prints a loving message.

Kotlin
fun main() {
    val animals = listOf("dog", "cat", "bird")
    for (animal in animals) {
        println("I love my $animal")
    }
}
OutputSuccess
Important Notes

You can use for loops with any collection like lists, sets, or arrays.

Inside the loop, you can use the current item to do calculations, print, or change values.

Remember, the loop runs once for each item in the collection.

Summary

A for loop repeats actions for every item in a collection.

Use it to easily work with lists, sets, or arrays.

It helps avoid writing repetitive code for each item.