6.4 Programming Exercise Set 4
6.4 Programming Exercise Set 4
383
One-Dimensional Arrays
Using a for loop, input values for the current and resistance arrays. The entries
in t he volts array should be the product of the corresponding values in the
current and resistance arrays (so volts[i] = current [i] *
resistance[i]). After all the data has been entered, display the following
output, with the appropriate value under each c olumn heading:
Current
Resistance
Volts
7.2
Array Initialization
Array elements can be initialized in their declaration statements in the same
manner as scalar variables, except the initializing elements must be included in
braces, as shown in these examples:
Initializers are applied in the order they are written, with the first value used to
initialize element 0, the second value used to initialize element 1, and so on, until
all values have been used. For example, in the declaration
temp [0] is initialized to 98, temp [1] is initialized to 87, temp [2] is initialized to
92, temp [3] is initialized to 79, and temp [4] is initialized to 85.
Because white space is ignored in C++, initializations can be continued across
multiple lines. For example, the following declaration uses four lines to initialize
all the array elements:
only length[0], length[1], length[2], and length[3] are initialized with the
listed values. The other array elements are initialized to 0.
Unfortunately, there's no method of indicating repetition of an initialization value
or of initializing later array elements without first specifying values for earlier
elements.
A unique feature of initializers is that the array size can be omitted when
initializing values are included in the declaration statement. For example,
the following declaration reserves enough storage room for five elements: