Sex offenders web site - 316 Arrays Chapter 7 Let us examine array

316 Arrays Chapter 7 Let us examine array cin Figure 7.1 more closely. The name of the array is c. Every array in Java knows its own length and maintains this information in a variable called length. The expression c.length accesses array c s length variable to determine the length of the array. The array s 12 elements are referred to as c[0], c[1], c[2], , c[11]. The value of c[0]is -45, the value of c[1] is 6, the value of c[2] is 0, the value of c[7] is 62and the value of c[11] is 78. To calculate the sum of the values contained in the first three elements of array cand store the result in variable sum, we would write sum = c[ 0 ] + c[ 1 ] + c[ 2 ]; To divide the value of the seventh element of array cby 2and assign the result to the variable x, we would write x=c[ 6]/ 2; Common Programming Error 7.1 It is important to note the difference between the seventh element of the array and array element seven. Because array subscripts begin at 0, the seventh element of the array has a subscript of 6, while array element seven has a subscript of 7 and is actually the eighth element of the array. This confusion is a source of off-by-one errors. The brackets used to enclose the subscript of an array are one of Java s many operators. Brackets are in the highest level of precedence in Java. The chart in Fig. 7.2 shows the precedence and associativity of the operators introduced so far. They are shown top to bottom in decreasing order of precedence with their associativity and type. See Appendix C for the complete operator precedence chart. Operators Associativity Type () [] . left to right highest ++ –right to left unary postfix ++ –+ -! (type) right to left unary * / % left to right multiplicative + -left to right additive < <= > >= left to right relational == != left to right equality & left to right boolean logical AND ^ left to right boolean logical exclusive OR | left to right boolean logical inclusive OR && left to right logical AND || left to right logical OR ?: right to left conditional = += -= *= /= %= right to left assignment Fig. 7.2Precedence and associativity of the operators discussed so far. Fig. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

Leave a Reply