Bird
0
0

Which of the following is the correct way to print both index and value from a list names using withIndex() in Kotlin?

easy📝 Conceptual Q2 of 15
Kotlin - Loops and Ranges
Which of the following is the correct way to print both index and value from a list names using withIndex() in Kotlin?
Afor (i in names) { println(i) }
Bfor (name in names.withIndex()) { println(name) }
Cfor ((i, name) in names.withIndex()) { println("$i: $name") }
Dfor (i in names.indices) { println(names[i]) }
Step-by-Step Solution
Solution:
  1. Step 1: Identify correct destructuring syntax

    The correct syntax to get index and value is for ((i, name) in names.withIndex()).
  2. Step 2: Confirm print format

    Inside the loop, printing "$i: $name" shows index and value clearly.
  3. Final Answer:

    for ((i, name) in names.withIndex()) { println("$i: $name") } -> Option C
  4. Quick Check:

    Destructuring with withIndex() = for ((i, name) in names.withIndex()) { println("$i: $name") } [OK]
Quick Trick: Use (index, value) to destructure withIndex() pairs [OK]
Common Mistakes:
MISTAKES
  • Not destructuring pairs
  • Using indices without values
  • Printing pairs directly without destructuring

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes