Recall & Review
beginner
What is the purpose of a
for loop when used with collections in Kotlin?A
for loop lets you go through each item in a collection one by one, so you can work with each element easily.Click to reveal answer
beginner
How do you write a basic
for loop to print all elements in a list named fruits?You write: <br>
for (fruit in fruits) {
println(fruit)
}<br>This goes through each fruit and prints it.Click to reveal answer
beginner
Can you use a
for loop with different types of collections in Kotlin?Yes! You can use
for loops with lists, sets, arrays, and other collections because they all support iteration.Click to reveal answer
intermediate
What happens if you modify a collection inside a
for loop in Kotlin?Modifying a collection while looping over it can cause errors or unexpected behavior. It's safer to avoid changing the collection during iteration.
Click to reveal answer
intermediate
How can you access both the index and the value of elements in a collection using a
for loop?Use
for ((index, value) in collection.withIndex()) to get both the position and the item at the same time.Click to reveal answer
Which keyword is used to loop over each element in a Kotlin collection?
✗ Incorrect
The
for keyword is used to iterate over collections in Kotlin.What does this code print?<br>
val nums = listOf(1, 2, 3)
for (n in nums) {
print(n)
}✗ Incorrect
The loop prints each number without spaces, so the output is '123'.
How do you get both index and value in a Kotlin for loop?
✗ Incorrect
Using
withIndex() lets you access both index and value.Which collection types can you use a for loop with in Kotlin?
✗ Incorrect
Kotlin supports iteration over many collection types including Lists, Sets, and Arrays.
What is a risk when modifying a collection inside a for loop?
✗ Incorrect
Changing a collection while looping can cause errors or unexpected results.
Explain how to use a for loop to iterate over a list in Kotlin and print each element.
Think about the keyword 'for' and how you name each item in the loop.
You got /3 concepts.
Describe how to access both the index and value of elements in a Kotlin collection during a for loop.
Use parentheses and 'in' keyword together.
You got /3 concepts.