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
// CherryInside 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) // 50The same syntax works with any list type, whether it contains strings, numbers, or other values.
Challenge
MediumWrite 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
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorAugmented AssignmentComparison OperatorsRecap - Simple Math7Basic IO
Println FunctionString TemplatesReadLine InputType ConversionRecap - Years Until RetirementRecap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesNamed ArgumentsDefault ValuesSingle Expression FunctionsRecap - Sigma FunctionRecap - Validation Function13Iterating Over Sequences
Iterating Over ElementsWithIndex MethodIterating Over Strings P1Iterating Over Strings P2Recap - Indexed Letters2Variables
Val vs VarType InferenceNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Logical Operators Part 3Ternary With If ExpressionRecap - Simple Logic8Bill Split Calculator
Welcome MessageGetting Input3Nullability
What Is Null SafetyNullable TypesSafe Call OperatorElvis OperatorFunction Challenge BasicsNot Null AssertionRecap - Safe Access6Decision Making
If StatementIf - ElseIf As An ExpressionWhen ExpressionWhen With RangesRecap - Simple Calculator9Loops
For LoopWhile LoopDo-While LoopBreakContinueRanges In LoopsNested LoopRecap - FactorialRecap - Dynamic InputPractice on your own: Kotlin playground