Bird
Raised Fist0
Kotlinprogramming~10 mins

For loop over collections in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - For loop over collections
Start
↓
Get collection
↓
Take first element
↓
Execute loop body with element
↓
More elements?
No→End
Yes↓
Take next element
The loop starts by getting the collection, then takes each element one by one, runs the loop body, and repeats until no elements remain.
Execution Sample
Kotlin
val fruits = listOf("apple", "banana", "cherry")
for (fruit in fruits) {
    println(fruit)
}
This code loops over a list of fruits and prints each fruit.
Execution Table
Iterationfruit valueActionOutput
1"apple"Print fruitapple
2"banana"Print fruitbanana
3"cherry"Print fruitcherry
--No more elements, loop ends-
💡 All elements in the collection have been processed, loop ends.
Variable Tracker
VariableStartAfter 1After 2After 3Final
fruitundefined"apple""banana""cherry"undefined
Key Moments - 2 Insights
Why does the variable 'fruit' change each iteration?
Because in each iteration, 'fruit' takes the next element from the collection, as shown in execution_table rows 1 to 3.
What happens when the loop reaches the last element?
After printing the last element, the loop checks for more elements, finds none, and ends (see last row in execution_table).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'fruit' in iteration 2?
A"apple"
B"banana"
C"cherry"
Dundefined
💡 Hint
Check the 'fruit value' column in the second row of execution_table.
At which iteration does the loop stop running?
AAfter iteration 3
BAfter iteration 1
CAfter iteration 2
DIt never stops
💡 Hint
Look at the exit_note and the last row of execution_table.
If the collection had 4 elements, how would the execution_table change?
AThe output would be empty
BThe loop would stop after 3 iterations anyway
CThere would be 4 iterations with fruit values for each element
DThe loop would run infinitely
💡 Hint
Refer to how each element corresponds to one iteration in execution_table.
Concept Snapshot
For loop over collections in Kotlin:
for (item in collection) {
    // use item
}
Loops through each element in the collection one by one.
The loop variable takes each element in order.
Loop ends when all elements are processed.
Full Transcript
This visual execution shows how a Kotlin for loop works over a collection. The loop starts by getting the collection and then takes each element one by one. In each iteration, the loop variable 'fruit' holds the current element. The loop body prints the fruit. After the last element is processed, the loop ends. The variable tracker shows how 'fruit' changes each iteration. Key moments clarify why 'fruit' changes and when the loop stops. The quiz tests understanding of variable values and loop termination.

Practice

(1/5)
1. What does a for loop do when used with a collection in Kotlin?
easy
A. It sorts the collection automatically.
B. It creates a new collection from the existing one.
C. It removes items from the collection one by one.
D. It repeats a block of code for each item in the collection.

Solution

  1. Step 1: Understand the purpose of a for loop

    A for loop runs code repeatedly for each element in a collection like a list or array.
  2. Step 2: Identify what happens in the loop

    Each item is accessed one by one, and the code inside the loop runs for each item.
  3. Final Answer:

    It repeats a block of code for each item in the collection. -> Option D
  4. Quick Check:

    For loop = repeat for each item [OK]
Hint: For loops run code once per item in a collection [OK]
Common Mistakes:
  • Thinking for loop creates or removes items
  • Confusing for loop with sorting or filtering
  • Believing for loop runs only once
2. Which of the following is the correct syntax for a for loop over a list named items in Kotlin?
easy
A. for item in items { println(item) }
B. for (item in items) { println(item) }
C. for item : items { println(item) }
D. for (item : items) println(item)

Solution

  1. Step 1: Recall Kotlin for loop syntax

    Kotlin requires parentheses around the loop variable and collection: for (item in items) { ... }
  2. Step 2: Check each option

    for (item in items) { println(item) } matches the correct syntax with parentheses and braces.
  3. Final Answer:

    for (item in items) { println(item) } -> Option B
  4. Quick Check:

    Parentheses + in keyword = correct syntax [OK]
Hint: Use parentheses and 'in' keyword in Kotlin for loops [OK]
Common Mistakes:
  • Omitting parentheses around loop header
  • Using colon ':' instead of 'in'
  • Missing braces for loop body
3. What is the output of this Kotlin code?
val numbers = listOf(1, 2, 3)
for (num in numbers) {
    print(num * 2)
}
medium
A. 246
B. 123
C. 6
D. Error

Solution

  1. Step 1: Understand the loop and list

    The list contains 1, 2, 3. The loop goes through each number.
  2. Step 2: Calculate output for each iteration

    Each number is multiplied by 2 and printed without spaces: 1*2=2, 2*2=4, 3*2=6, so output is "246".
  3. Final Answer:

    246 -> Option A
  4. Quick Check:

    Print doubles of 1,2,3 = 246 [OK]
Hint: Multiply and print each item in order [OK]
Common Mistakes:
  • Assuming print adds spaces or newlines
  • Confusing multiplication with addition
  • Expecting a list output instead of concatenated string
4. Identify the error in this Kotlin code snippet:
val fruits = listOf("apple", "banana", "cherry")
for fruit in fruits {
    println(fruit)
}
medium
A. Missing parentheses around loop header
B. Using wrong collection type
C. Incorrect print statement
D. No error, code is correct

Solution

  1. Step 1: Check for correct for loop syntax

    Kotlin requires parentheses around the loop header: for (fruit in fruits) { ... }
  2. Step 2: Identify the missing parentheses

    The code misses parentheses around 'fruit in fruits', causing a syntax error.
  3. Final Answer:

    Missing parentheses around loop header -> Option A
  4. Quick Check:

    Parentheses required in Kotlin for loops [OK]
Hint: Always put parentheses around for loop header [OK]
Common Mistakes:
  • Omitting parentheses in for loop
  • Using wrong loop variable syntax
  • Assuming print statement causes error
5. Given a list of names, how would you use a Kotlin for loop to print only names longer than 4 characters? Choose the correct code snippet.
hard
A. for (name in names) { println(name.length) > 4 }
B. for (name in names) println(name.length > 4)
C. for (name in names) { if (name.length > 4) println(name) }
D. for (name in names) { if (name > 4) println(name) }

Solution

  1. Step 1: Understand the condition to filter names

    We want to print names only if their length is greater than 4 characters.
  2. Step 2: Check each option for correct syntax and logic

    for (name in names) { if (name.length > 4) println(name) } correctly uses an if statement inside the loop to check length and print the name.
  3. Final Answer:

    for (name in names) { if (name.length > 4) println(name) } -> Option C
  4. Quick Check:

    Use if inside for to filter by length [OK]
Hint: Use if condition inside for loop to filter items [OK]
Common Mistakes:
  • Comparing string directly to number
  • Printing boolean instead of name
  • Incorrect syntax in if or print statements
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard