Title: Array Element Reference Examples
Course: CPS 120: Introduction to Computer Science ~ Master (Aug/2015) OLD > Section: Learning Units

Array element reference examples
Flags[0] = true; | Assigns the value true to the first element (0) in array Flags.
Salaries[10] = 15000.25; | Assigns the value 15000.25 to the eleventh element (10) in array Salaries.
for (j = 0; j < 4; j = j + 1) {
cout << "Enter the next score: ";
cin >> Scores[j];
}
Loops to read four values into array Scores.
for (j = 0; j < 7; j = j + 1) { cout << DaysOfWeek[j] << endl; } | Loops to write seven values from array DaysOfWeek.

- The index ranges in value from zero to the array length minus one.
- Visual C++ does not check whether an index is within an array’s bounds.  If an index goes beyond the last element in the array, execution of the rest of the program is unpredictable.

Arrays and For loops

- For loops and arrays are often used together.
- Two or more arrays of the same size may be defined to hold information in a database-like faction. These are called parallel arrays.

Example 1: declare two arrays with six slots each, assign values to each array element, and loop (For) to display the values.

int i;
int Years[6];
double Averages[6];

Years[0] = 1958;
Years[1] = 1968;
Years[2] = 1978;
Years[3] = 1988;
Years[4] = 1998;
Years[5] = 2008;

Averages[0] = 2.32;
Averages[1] = 2.18;
Averages[2] = 2.22;
Averages[3] = 1.81;
Averages[4] = 1.39;
Averages[5] = 3.34;

cout << "Average Prices Per Gallon By Year" << endl;
cout << " Adjusted For Inflation" << endl << endl;
cout << "\tYear\tPrice" << endl;

for (i = 0; i < 6; i = i + 1) {
cout << "\t" << Years[i]
<< "\t$" << Averages[i] << endl;
}

cout << endl << "End of Report!" << endl;