Bird
0
0

How can you use a for loop to create a new list of squares from an existing list of integers in Kotlin?

hard📝 Application Q9 of 15
Kotlin - Loops and Ranges
How can you use a for loop to create a new list of squares from an existing list of integers in Kotlin?
Aval squares = numbers.forEach { it * it }
Bval squares = mutableListOf<Int>(); for (n in numbers) { squares.add(n * n) }
Cfor (n in numbers) { val squares = n * n }
Dval squares = listOf<Int>(); for (n in numbers) { squares.add(n * n) }
Step-by-Step Solution
Solution:
  1. Step 1: Initialize a mutable list to store results

    Use mutableListOf() to create an empty list that can be added to.
  2. Step 2: Loop through numbers and add squares

    Inside the loop, calculate n * n and add to squares list.
  3. Final Answer:

    val squares = mutableListOf(); for (n in numbers) { squares.add(n * n) } -> Option B
  4. Quick Check:

    Use mutable list and add inside loop [OK]
Quick Trick: Use mutableListOf and add() inside for loop [OK]
Common Mistakes:
MISTAKES
  • Using immutable list and trying to add
  • Reinitializing list inside loop
  • Using forEach which returns Unit

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes