This chapter introduces arrays, a common multi-dimensional data structure used to store data of the same type. (Note that a class is a "data type" in this sense.) Arrays have some number of dimensions and a number of elements in each dimension. These are established when the array is created. The range of the array's index in each dimension goes from zero to the number of that dimension's elements minus one. A for loop is commonly used to initialize, manipulate, and access the values in an array. Here, we treat one-dimensional arrays, sometimes called vectors.
4. Arithmetic Expressions
Answer:
23
data[2]
contains a 14 and data[6]
contains a 9, the sum is 23.
Arithmetic Expressions
An expression such as
data[3]
is
called a subscripted variable.
A subscripted variable can be used anywhere an ordinary variable of the same type can be used. Since data[3]
contains an int
it can be used anywhere an int
variable may be used.
An arithmetic expression can contain a mix of literals, variables, and subscripted variables. For example, if x
contains a 10, then
(x + data[2]) / 4
evaluates to (10+14) / 4 == 6. Here are some other legal statements:
data[0] = (x + data[2]) / 4 ;
data[2] = data[2] + 1;
// increment the data in cell 3
x = data[3]++ ;
data[4] = data[1] / data[6];
Question 4:
Assume that the array holds values as in the picture. What will be the result of executing the statement:
data[0] = data[6] + 8;