C++ Notes: Array Examples

Example -- adding all elements of an array

This program values into an array and sum them. Assume fewer than 1000 input values. Yes, we could have summed them in the input loop.
  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
// arrays/readsum.cpp -- Read numbers into an array and sum them.
// Fred Swartz - 2003-11-20

#include <iostream>
using namespace std;

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

    while (cin >> a[n]) {
        n++;
    }

    int sum = 0;       // Start the total sum at 0.
    for (int i=0; i<n; i++) {
        sum = sum + a[i];  // Add the next element to the total
    }
    
    cout << sum << endl;
    
    return 0;
}

Why read numbers into memory

The previous example, which reads numbers into an array then sums the elements of the array, is not a convincing use of arrays. It would have been just as easy to add them while we were reading them.

But usually the computation 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.
  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
// arrays/reverse-input.cpp - Reverses order of numbers in input.
#include <iostream>
using namespace std;

int main() {
    //--- Declare array and number of elements in it.
    float a[100000];
    int n;   // Number of values currenlty in array.
   
    //--- Read numbers into an array
    n = 0;
    while (cin >> a[n]) {
        n++;
    }
   
    //--- Print array in reverse order
    for (int i=n-1; i>=0; i--) {
        cout << a[i] << endl;
    }
   
    return 0;
}//end main