Bird
0
0

How can you use repeat to create a list of squares of numbers from 0 to 4 in Kotlin?

hard📝 Application Q15 of 15
Kotlin - Loops and Ranges
How can you use repeat to create a list of squares of numbers from 0 to 4 in Kotlin?
Aval squares = mutableListOf<Int>(); repeat(5) { squares.add(it * it) }
Bval squares = repeat(5) { it * it }
Cval squares = List(5) { repeat(it * it) }
Dval squares = repeat(5) { println(it * it) }
Step-by-Step Solution
Solution:
  1. Step 1: Understand repeat usage for list building

    The repeat function runs code multiple times but does not return a list itself.
  2. Step 2: Check each option's approach

    val squares = mutableListOf(); repeat(5) { squares.add(it * it) } creates a mutable list and adds squares inside repeat, which works. val squares = repeat(5) { it * it } tries to assign repeat's result directly, which is Unit (no list). val squares = List(5) { repeat(it * it) } misuses List and repeat. val squares = repeat(5) { println(it * it) } only prints values, no list created.
  3. Final Answer:

    val squares = mutableListOf(); repeat(5) { squares.add(it * it) } -> Option A
  4. Quick Check:

    repeat + add to list = correct list [OK]
Quick Trick: Use repeat to add items to a mutable list [OK]
Common Mistakes:
MISTAKES
  • Expecting repeat to return a list
  • Using repeat inside List constructor incorrectly
  • Only printing values without storing

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes