C++ Notes: Arrays continued

Why read numbers into memory

The previous example which reads numbers into memory then adds them up is not a convincing use of arrays. It would have been just as easy to add them while we were reading them.

But often there are operations that can not be performed while reading, for example, sorting them and printing them in order by their value. An even simpler example is given below - printing them in reverse order of input.

Example -- printing the input values last to first

Here is something than can't be done with a simple input loop.
int a[1000];       // Declare an array of 1000 ints
int n = 0;         // number of values in a.
. . .
while (cin >> a[n]) {
    n++;
}
. . .
// print the array elements starting at the end.
// Note that n is the subscript of the next empty 
//      array position, not the last filled one
//      and that the first element is in a[0].
for (int i=n-1; i>=0; i--) {
    cout << a[i];  
}

Initializing an array in the declaration

An array can be initialized in the declaration. If the size is omitted, the compiler will determine the size from the number of values. For example,
int days[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
// is the same as the statement below:
int days[] = {31,28,31,30,31,30,31,31,30,31,30,31};

Array variables as parameters

When an array is passed as a parameter, only the memory address of the array is passed (not all the values). An array as a parameter is declared similarly to an array as a variable, but no bounds are specified. The function doesn't know how much space is allocated for an array. See the example below.

Example -- function to add numbers

This main program calls a function to add all the elements in an array and uses the returned value to compute the average.
#include <iostream>
using namespace std;

float sum(float x[], int size); // prototype

int main() {
    float a[1000];     // Declare an array of 1000 ints
    int n = 0;         // number of values in a.

    while (cin >> a[n]) {
        n++;
    }
    
    cout << "Average = " << sum(a, n)/n << endl;
    
    return 0;
}//end main

// sum adds the values of the array it is passed.
float sum(float x[], int size) {
    float total = 0.0;  // the sum is accumulated here
    for (int i=0; i<size; i++) {
        total += x[i];  
    }
    return total;
}//end sum