Bird
0
0

Which of the following is the correct syntax to create an array of size 5 with all elements initialized to zero in Kotlin?

easy📝 Syntax Q12 of 15
Kotlin - Collections Fundamentals
Which of the following is the correct syntax to create an array of size 5 with all elements initialized to zero in Kotlin?
A<code>val arr = Array(5, 0)</code>
B<code>val arr = Array(0, 0, 0, 0, 0)</code>
C<code>val arr = Array(5) { 0 }</code>
D<code>val arr = IntArray(5, 0)</code>
Step-by-Step Solution
Solution:
  1. Step 1: Understand Array constructor usage

    Kotlin's Array(size) { init } creates an array of given size, initializing each element with the lambda result.
  2. Step 2: Evaluate options

    val arr = Array(5) { 0 } correctly uses Array(5) { 0 } to create an array of 5 zeros. val arr = Array(0, 0, 0, 0, 0) is invalid syntax. val arr = Array(5, 0) is invalid syntax. val arr = IntArray(5, 0) is invalid because IntArray constructor takes only size or size with init lambda, not two parameters.
  3. Final Answer:

    val arr = Array(5) { 0 } -> Option C
  4. Quick Check:

    Use Array(size) { value } to initialize [OK]
Quick Trick: Use Array(size) with lambda to initialize all elements [OK]
Common Mistakes:
MISTAKES
  • Passing two parameters to Array constructor incorrectly
  • Confusing IntArray constructor parameters
  • Passing multiple values directly to Array constructor

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes