Array Length and the Standard for Loop

Part of: Array

The length Field Every array carries a public field named length that reports how many elements it holds: Note: length is a field, not a method , so there are no parentheses. (Strings use .length() with parentheses, arrays use .length without. A classic mix-up.) Traversing with a for Loop The standard way to visit every element is a for loop driven by an index that runs from 0 up to length - 1: Break down the three parts: - Initialization: int i = 0 starts at the first index. - Condition: i < a.length keeps going while i is a valid index. Using < (not <=) is essential. - Update: i++ advances to the next slot. Why i < a.length, Not i <= a.length If an array has length 4, the valid indices are 0, 1, 2, 3. Writing i <= a.length would try to access a[4], which does not exist and throws an error. Always pair < with length. Index Variable Reuse Because the loop exposes the index i, you can do index-dependent work, like printing positions: Using a.length rather than a hard-coded number means your loop adapts automatically if the array size changes. This is the most important traversal pattern in the AP CS A course, and you will reuse it constantly.

Challenge: Sum and Length Report