Bird
0
0

Given int[] nums = {10, 20, 30, 40, 50};, which loop correctly prints all elements using the array's length property?

hard📝 Application Q8 of 15
Java - Arrays
Given int[] nums = {10, 20, 30, 40, 50};, which loop correctly prints all elements using the array's length property?
Afor(int i = 1; i <= nums.length; i++) { System.out.print(nums[i] + " "); }
Bfor(int i = 0; i < nums.length; i++) { System.out.print(nums[i] + " "); }
Cfor(int i = 0; i <= nums.length; i++) { System.out.print(nums[i] + " "); }
Dfor(int i = 1; i < nums.length; i++) { System.out.print(nums[i] + " "); }
Step-by-Step Solution
Solution:
  1. Step 1: Understand array indexing

    Array indices start at 0 and go up to length - 1.
  2. Step 2: Analyze each option

    for(int i = 0; i < nums.length; i++) { System.out.print(nums[i] + " "); } correctly loops from 0 to nums.length - 1. Options B and D start at 1, missing the first element. for(int i = 0; i <= nums.length; i++) { System.out.print(nums[i] + " "); } goes to nums.length, causing an IndexOutOfBoundsException.
  3. Final Answer:

    for(int i = 0; i < nums.length; i++) { System.out.print(nums[i] + " "); } -> Option B
  4. Quick Check:

    Loop from 0 to length-1 to access all elements. [OK]
Quick Trick: Loop from 0 to length-1 for arrays. [OK]
Common Mistakes:
  • Starting loop at 1 instead of 0
  • Using <= length instead of < length
  • Ignoring zero-based indexing

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes