6.7 Programming Exercise Set 5
6.7 Programming Exercise Set 5
6.7 Programming Exercise Set 5
EXERCISES 7.3
int main()
return 0;
3. (Practice) a. Write a C++ program that adds the values of all
elements in the val array
used in Exercise 2 and displays the total.
b. Modify the program written for Exercise 3a to display the total of each row
separately.
16 54
first
18 91
23 11
second 24 52 16 19
77 59
5. (Data Processing) a. Write a C++ program that finds and displays the
maximum value
in a two-dimensional array of integers. The array should be declared as a 4-by-5
array of integers and initialized with the data 16, 22, 99, 4, 18, -258, 4, 101, 5, 98,
105, 6, 15, 2, 45, 33, 88, 72, 16, and 3. b. Modify the program written in
Exercise 5a so that it also displays the maximum val
ue's row and column subscript numbers.
394
Arrays
ata Processing) Write a C++ program that selects the values in a 4-by-5 array of
6. (D
posi
tive integers in increasing order and stores the selected values in the
one-dimensional array named sort. Use the data statement in Exercise 5a to
initialize the two dimensional array.
Passing a complete array of values to a function is, in many respects, easier than
passing e ach element. The called function receives access to the actual array
rather than a copy of values in the array. For example, if volts is an array, the
function call findMax (volts); makes the complete volts array available to the findMax
() function. This function call is different from passing a single variable to a function.
Recall that when a single scalar argument is passed to a function (see Section 6.1), the
called function receives only a copy of the passed value, which is stored in one of the
function's parameters. If arrays were passed in this manner, a copy of the
complete array would have to be created. For large arrays, making copies for each
function call would waste computer storage and frustrate the effort to return
multiple-element changes made by the called program. (Remember that a function
returns at most one direct value.)
To avoid these problems, the called function is given direct access to the original array,3 In
this way, any changes the called function makes are made directly to the array. For
the following specific examples of function calls, the arrays nums, keys, volts, and
current are declared as shown:
int nums [5]; char keys [256]; double volts (500), current[500);
// a n array of five integers 1 / an array of 256 characters // t wo arrays of 500
doubles
3The called function has access to the original array because the array's starting address is actually passed
as an argument. The formal parameter receiving this address argument is a pointer. Chapter 12 explains the
intimate relationship between array names and pointers.