previous | start | next

## Arrays

- Declaring an array is very similar to declaring a vector.

  >     double salaries[10]; /* array */

  >     /* compare to.... */
  >     vector<double> salaries(10);

- Arrays can never change size.
- The array size must be set when the program is compiled. (You can't ask the user how many elements and then allocate a sufficient number).
- When defining an array, you must guess on the maximum number of elements you need to store.

  >     const int SALARIES_CAPACITY = 100;
  >     double salaries[SALARIES_CAPACITY];

- You must keep a constant to hold the capacity of the array.
- You must keep a companion variable that counts how many elements are actually used.

  >     int salaries_size = 0;
  >     while (more && salaries_size < SALARIES_CAPACITY)
  >     {
  >        cout << "Enter salary or 0 to quit: ";
  >        double x;
  >        cin >> x;
  >        if (cin.fail() || x == 0)
  >           more = false;

  >        else
  >        {
  >           salaries[salaries_size] = x;
  >           salaries_size++;
  >        }
  >     }

previous | start | next