Bird
Raised Fist0
Kotlinprogramming~20 mins

For loop with index (withIndex) in Kotlin - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
For Loop with Index Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate
2:00remaining
Output of for loop with withIndex on a list
What is the output of this Kotlin code snippet?
val fruits = listOf("apple", "banana", "cherry")
for ((index, fruit) in fruits.withIndex()) {
    println("$index: $fruit")
}
Kotlin
val fruits = listOf("apple", "banana", "cherry")
for ((index, fruit) in fruits.withIndex()) {
    println("$index: $fruit")
}
A
apple: 0
banana: 1
cherry: 2
B
0: apple
1: banana
2: cherry
C
apple
banana
cherry
D
0: apple
1: banana
2: cherry
3: null
Attempts:
2 left
💡 Hint
Remember that withIndex() provides both the index and the element in the loop.
📝 Syntax
intermediate
2:00remaining
Identify the syntax error in for loop with withIndex
Which option contains a syntax error in using withIndex() in a for loop?
Kotlin
val numbers = listOf(10, 20, 30)
for ((i, num) in numbers.withIndex()) {
    println("Index $i has value $num")
}
Afor ((i, num) in numbers.withIndex()) { println(i + num) }
B} )mun + i(nltnirp { ))(xednIhtiw.srebmun ni )mun ,i(( rof
Cfor ((i, num) in numbers.withIndex()) println(i + num)
Dfor (i, num in numbers.withIndex()) { println(i + num) }
Attempts:
2 left
💡 Hint
Check how destructuring declarations are used in Kotlin for loops.
❓ optimization
advanced
2:00remaining
Optimizing iteration with withIndex on large lists
Given a large list, which approach is more efficient to print index and value pairs?
Options:
A) Using withIndex() in a for loop
B) Using indices property and accessing elements by index
C) Using forEachIndexed function
D) Using a while loop with manual index increment
Afor ((index, value) in list.withIndex()) { println("$index: $value") }
Bfor (i in list.indices) { println("$i: ${list[i]}") }
Clist.forEachIndexed { index, value -> println("$index: $value") }
D
var i = 0
while (i < list.size) { println("$i: ${list[i]}"); i++ }
Attempts:
2 left
💡 Hint
Consider readability and internal optimizations of Kotlin standard library functions.
🔧 Debug
advanced
2:00remaining
Debug the unexpected output in for loop with withIndex
What causes this Kotlin code to print incorrect indices?
val items = listOf("a", "b", "c")
for ((index, item) in items.withIndex()) {
    if (item == "b") continue
    println("$index: $item")
}
AThe continue statement skips printing but does not skip index increment, so indices remain correct.
BThe loop should use break instead of continue to avoid index issues.
CThe index variable is not updated correctly because of continue, causing wrong indices.
DUsing continue inside for loop with withIndex causes index to reset to 0.
Attempts:
2 left
💡 Hint
Think about how continue affects loop iteration and index values.
🧠 Conceptual
expert
2:00remaining
Understanding withIndex behavior on different collections
Which statement about withIndex() in Kotlin is TRUE?
AwithIndex() can be used on any Iterable and returns an IndexedValue sequence with index starting at 0.
BwithIndex() modifies the original collection by adding index properties to elements.
CwithIndex() returns indices and values only for List collections, not for Sets.
DwithIndex() returns a Map of index to element for any collection.
Attempts:
2 left
💡 Hint
Recall what types of collections implement Iterable and how withIndex works.

Practice

(1/5)
1. What does the withIndex() function do in a Kotlin for loop?
easy
A. It filters elements based on their index.
B. It sorts the list before looping.
C. It provides both the index and the value of each element during iteration.
D. It reverses the list before looping.

Solution

  1. Step 1: Understand the purpose of withIndex()

    The withIndex() function returns an iterable of pairs containing the index and the value of each element in the collection.
  2. Step 2: Identify what the loop receives

    Using withIndex() in a for loop allows access to both the position (index) and the element (value) simultaneously.
  3. Final Answer:

    It provides both the index and the value of each element during iteration. -> Option C
  4. Quick Check:

    withIndex() = index + value [OK]
Hint: Remember: withIndex() gives index and value together [OK]
Common Mistakes:
  • Thinking it sorts or filters the list
  • Assuming it reverses the collection
  • Confusing index with value only
2. Which of the following is the correct syntax to loop over a list items with index in Kotlin?
easy
A. for ((index, value) in items.withIndex()) { /* code */ }
B. for (index, value in items) { /* code */ }
C. for (index; value in items.withIndex()) { /* code */ }
D. for index, value in items.withIndex() { /* code */ }

Solution

  1. Step 1: Recall Kotlin destructuring syntax in loops

    Kotlin allows destructuring pairs using parentheses in the for loop header, like for ((index, value) in ...).
  2. Step 2: Match syntax with withIndex()

    The correct syntax uses items.withIndex() and destructures the pair into index and value.
  3. Final Answer:

    for ((index, value) in items.withIndex()) { /* code */ } -> Option A
  4. Quick Check:

    Destructure pairs with (index, value) [OK]
Hint: Use parentheses to destructure pairs in for loop [OK]
Common Mistakes:
  • Omitting parentheses around (index, value)
  • Using semicolon instead of comma
  • Missing 'in' keyword
3. What will be the output of this Kotlin code?
val data = listOf("apple", "banana", "cherry")
for ((i, v) in data.withIndex()) {
    println("$i: $v")
}
medium
A. 0: apple 1: banana 2: cherry
B. apple: 0 banana: 1 cherry: 2
C. 1: apple 2: banana 3: cherry
D. Error: cannot destructure

Solution

  1. Step 1: Understand the list and loop

    The list contains three fruits: "apple", "banana", "cherry". The loop uses withIndex() to get index and value.
  2. Step 2: Trace the loop output

    Each iteration prints the index and value separated by colon and space. Indices start at 0.
  3. Final Answer:

    0: apple 1: banana 2: cherry -> Option A
  4. Quick Check:

    Index starts at 0, prints index: value [OK]
Hint: Index starts at 0 in withIndex() loops [OK]
Common Mistakes:
  • Assuming index starts at 1
  • Swapping index and value in output
  • Expecting error from destructuring
4. Identify the error in this Kotlin code snippet:
val numbers = arrayOf(10, 20, 30)
for (i, num in numbers.withIndex()) {
    println("$i -> $num")
}
medium
A. Cannot use withIndex() on arrays.
B. Missing parentheses around (i, num) in the for loop.
C. The println statement syntax is incorrect.
D. Variable names i and num are reserved keywords.

Solution

  1. Step 1: Check for correct destructuring syntax

    In Kotlin, destructuring pairs in a for loop requires parentheses: for ((i, num) in ...).
  2. Step 2: Verify other parts of the code

    Using withIndex() on arrays is valid. The println syntax and variable names are correct.
  3. Final Answer:

    Missing parentheses around (i, num) in the for loop. -> Option B
  4. Quick Check:

    Destructure pairs with parentheses [OK]
Hint: Always use parentheses to destructure pairs in for loops [OK]
Common Mistakes:
  • Omitting parentheses in destructuring
  • Thinking withIndex() doesn't work on arrays
  • Misreading println syntax
5. Given a list of database table names tables = listOf("users", "orders", "products"), how can you create a map of index to table name using a Kotlin for loop with withIndex()?
hard
A. val map = mutableMapOf() for (t in tables) { map[t] = t.length }
B. val map = mutableMapOf() for ((i, t) in tables.withIndex()) { map[t] = i }
C. val map = mutableMapOf() for (i in tables.withIndex()) { map[i] = tables[i] }
D. val map = mutableMapOf() for ((i, t) in tables.withIndex()) { map[i] = t }

Solution

  1. Step 1: Understand the goal

    We want a map where keys are indices (Int) and values are table names (String).
  2. Step 2: Use withIndex() to get index and value

    Loop over tables.withIndex() and assign map[i] = t to build the map correctly.
  3. Final Answer:

    val map = mutableMapOf() for ((i, t) in tables.withIndex()) { map[i] = t } -> Option D
  4. Quick Check:

    Index to value mapping with withIndex() [OK]
Hint: Use withIndex() and map[i] = value to build index-value map [OK]
Common Mistakes:
  • Swapping key and value types in map
  • Not destructuring with parentheses
  • Using wrong loop variable types
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