0
0
Kotlinprogramming~5 mins

For loop over collections in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Aloop
Bwhile
Cfor
Drepeat
What does this code print?<br>
val nums = listOf(1, 2, 3)
for (n in nums) {
    print(n)
}
A1 2 3
B123
C3 2 1
DError
How do you get both index and value in a Kotlin for loop?
Afor (index in collection)
Bfor (index, value in collection)
Cfor (value in collection.indices)
Dfor ((index, value) in collection.withIndex())
Which collection types can you use a for loop with in Kotlin?
ALists, Sets, Arrays
BOnly Lists
COnly Arrays
DOnly Sets
What is a risk when modifying a collection inside a for loop?
AIt can cause errors or unexpected behavior
BIt speeds up the loop
CIt makes the loop skip elements
DIt automatically copies the collection
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.