Menu
Coddy logo textTech

Iterating Over Elements

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 74 of 93.

Now that you know how to create and modify lists, it's time to learn how to process each element one by one. This is called iteration, and it's one of the most common operations you'll perform with lists.

The for loop provides a clean way to iterate over every element in a list:

val fruits = listOf("Apple", "Banana", "Cherry")
for (fruit in fruits) {
    println(fruit)
}
// Output:
// Apple
// Banana
// Cherry

Inside the loop, the variable fruit takes on each value from the list in order. You can name this variable anything that makes sense for your data. The loop automatically stops after processing the last element.

This pattern works great when you need to perform an action on each item, like calculating a total:

val prices = listOf(10, 25, 15)
var total = 0
for (price in prices) {
    total += price
}
println(total)  // 50

The same syntax works with any list type, whether it contains strings, numbers, or other values.

challenge icon

Challenge

Medium

Write a function countPositives that takes a list of integers and returns the count of positive numbers.

Iterate through each element in the list and count how many numbers are greater than zero.

Parameters:

  • numbers (List<Int>): A list of integers (can include positive, negative, and zero values)

Returns: The total count of positive numbers in the list (Int)

Try it yourself

fun countPositives(numbers: List<Int>): Int {
    // Write code here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Kotlin playground