Often, the elements of an array
represent a series of values to be used in a calculation. For example, if the elements of an array
represent exam grades, a professor may wish to total the elements of the array
and use that sum to calculate the class average for the exam.
The program in Fig. 7.8 sums the values contained in the four-element integer array a
. The program declares, creates and initializes the array
in line 10. The for
statement (lines 14–15) performs the calculations. The values being supplied as initializers for array a
also could be read into the program from the user at the keyboard, or from a file on disk (see Chapter 14, File Processing). For example, the for
statement
for ( size_t j = 0; j < a.size(); ++j )
cin >> a[ j ];
reads one value at a time from the keyboard and stores the value in element a[j]
.
1 // Fig. 7.8: fig07_08.cpp
2 // Computing the sum of the elements of an array.
3 #include <iostream>
4 #include <array>
5 using namespace std;
6
7 int main()
8 {
9 const size_t arraySize = 4; // specifies size of array
10 array< int, arraySize > a = { 10, 20, 30, 40 };
11 int total = 0;
12
13 // sum contents of array a
14 for ( size_t i = 0; i < a.size(); ++i )
15 total += a[ i ];
16
17 cout << "Total of array elements: " << total << endl;
18 } // end main
Total of array elements: 100