Arrays
Arrays
subscripts:
0 1 2 3 4
Accessing Array Elements
subscripts:
0 1 2 3 4
Accessing Array Elements
• Array elements can be used as regular variables:
tests[0] = 79;
cout << tests[0];
cin >> tests[1];
tests[4] = tests[0] + tests[1];
• Arrays must be accessed via individual
elements:
cout << tests; // not legal
(Program Continues)
Here are the contents of the hours array, with the values
entered by the user in the example output:
Accessing Array Contents
12 17 15 11
When this code is finished, the highest variable will contains the highest value
in the numbers array.
Finding the Lowest Value in an
Array
int count;
int lowest;
lowest = numbers[0];
for (count = 1; count < SIZE; count++)
{
if (numbers[count] < lowest)
lowest = numbers[count];
}
When this code is finished, the lowest variable will contains the lowest value in
the numbers array.
Using Parallel Arrays
• Parallel arrays: two or more arrays that
contain related data
• A subscript is used to relate arrays:
elements at same subscript are related
• Arrays may be of different types
Parallel Array Example
const int SIZE = 5; // Array size
int id[SIZE]; // student ID
double average[SIZE]; // course average
char grade[SIZE]; // course grade
...
for(int i = 0; i < SIZE; i++)
{
cout << "Student ID: " << id[i]
<< " average: " << average[i]
<< " grade: " << grade[i]
<< endl;
}
(Program Continues)
Program 7-12 (Continued)
The hours and payRate arrays are related through their subscripts:
Arrays as Function Arguments
• To pass an array to a function, just use the array
name:
showScores(tests);
• To define a function that takes an array
parameter, use empty [] for array argument:
void showScores(int []);
// function prototype
void showScores(int tests[])
// function header
Arrays as Function Arguments
• When passing an array to a function, it is common
to pass array size so that function knows how many
elements to process:
showScores(tests, ARRAY_SIZE);
• Array size must also be reflected in prototype,
header:
void showScores(int [], int);
// function prototype
void showScores(int tests[], int size)
// function header
7-38
(Program Continues)
Program 7-14 (Continued)
Modifying Arrays in Functions
// Header
void getExams(int exams[][COLS], int rows)
Example – The showArray
Function from Program 7-19
How showArray is Called
Summing All the Elements in a
Two-Dimensional Array
• Given the following definitions:
const int NUM_ROWS = 5; // Number of rows
const int NUM_COLS = 5; // Number of columns
int total = 0; // Accumulator
int numbers[NUM_ROWS][NUM_COLS] =
{{2, 7, 9, 6, 4},
{6, 1, 8, 9, 4},
{4, 3, 7, 2, 9},
{9, 9, 0, 3, 1},
{6, 2, 7, 4, 1}};
Summing All the Elements in a
Two-Dimensional Array
// Sum the array elements.
for (int row = 0; row < NUM_ROWS; row++)
{
for (int col = 0; col < NUM_COLS; col++)
total += numbers[row][col];
}