Bird
0
0

You want to create an IntArray of size 5 where each element is its index squared (0, 1, 4, 9, 16). Which Kotlin code correctly does this?

hard📝 Application Q8 of 15
Kotlin - Collections Fundamentals
You want to create an IntArray of size 5 where each element is its index squared (0, 1, 4, 9, 16). Which Kotlin code correctly does this?
Aval arr = Array(5) { it * it }
Bval arr = IntArray(5) { it * it }
Cval arr = IntArray(5) { it * 2 }
Dval arr = Array(5) { it * 2 }
Step-by-Step Solution
Solution:
  1. Step 1: Choose correct array type for integers

    IntArray is preferred for primitive int arrays.
  2. Step 2: Use initializer lambda to square index

    Initializer { it * it } correctly computes squares.
  3. Final Answer:

    val arr = IntArray(5) { it * it } -> Option B
  4. Quick Check:

    IntArray with square initializer = val arr = IntArray(5) { it * it } [OK]
Quick Trick: Use IntArray(size) { it * it } for squares [OK]
Common Mistakes:
MISTAKES
  • Using Array instead of IntArray for ints
  • Multiplying by 2 instead of squaring
  • Wrong initializer syntax

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes