Bird
0
0

Given an integer array arr of size 5 initialized as {2, 4, 6, 8, 10}, which code snippet correctly doubles each element's value?

hard📝 Application Q15 of 15
Java - Arrays

Given an integer array arr of size 5 initialized as {2, 4, 6, 8, 10}, which code snippet correctly doubles each element's value?

?
Afor(int i = 0; i < arr.length; i++) { arr[i] *= 2; }
Bfor(int i = 0; i <= arr.length; i++) { arr[i] = arr[i] * 2; }
Cfor(int i = 1; i < arr.length; i++) { arr[i] = arr[i] * 2; }
Dfor(int i = 0; i < arr.length - 1; i++) { arr[i] = arr[i] * 2; }
Step-by-Step Solution
Solution:
  1. Step 1: Understand array length and loop bounds

    The array length is 5, so valid indexes are 0 to 4. Loop must run from 0 to less than length.
  2. Step 2: Evaluate each option's loop condition

    for(int i = 0; i <= arr.length; i++) { arr[i] = arr[i] * 2; } uses i <= arr.length which causes out of bounds error at i=5. for(int i = 0; i < arr.length; i++) { arr[i] *= 2; } correctly uses i < arr.length. for(int i = 1; i < arr.length; i++) { arr[i] = arr[i] * 2; } starts at 1, missing index 0. for(int i = 0; i < arr.length - 1; i++) { arr[i] = arr[i] * 2; } stops at length-1, missing last element.
  3. Final Answer:

    for(int i = 0; i < arr.length; i++) { arr[i] *= 2; } -> Option A
  4. Quick Check:

    Loop from 0 to length-1 doubles all elements [OK]
Quick Trick: Use i < arr.length to avoid index errors [OK]
Common Mistakes:
  • Using <= arr.length causing errors
  • Starting loop at 1 missing first element
  • Stopping loop early missing last element

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes