sum array using length Example
The length of an array is accessed using the keyword length.This program uses length to sum all an array's elements.
It does this using a loop, each iteration of which accesses a single element of the array determined by the loop counter.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Array Length Example, sum of an array
class ArrayLengthExample {
public static void main(String[] args) {
int[] ia = {12,20,18};
int len = ia.length;
int total = 0;
for(int i = 0; i < len; i++) {
total += ia[i];
}
}
}
8 The dot operator after an array's name and followed by length yields the length of an array.
The keyword length cannot be used to set the length of an array.
12-14 i is the loop counter and is initialized to 0.
Initializing a counter to 0, rather than 1, can be convenient if a loop is processing an array.
This is because Java's arrays are indexed from zero and the loop counter can be used to index each item if it too is first initialized to zero.
The loop accesses each element of the array.
Notice how the condition is expressed. It ensures that i takes the values 0 1 2 i.e. to one less than the length of the array. When it takes the value 3 the condition becomes false and the loop terminates.
The expression ia[i] yields the value of the array element with index i. The index can be any expression that evaluates to an int.
So in this loop, on each iteration, the value of each element is added into the variable total.
