Array Points
Array Points
PROGRAMMING
LECTURE # ARRAYS
1
NO BOUNDS CHECKING IN C++
12 17 15 11
tests[i++]; // increment i, no
// effect on tests
COPYING AN ARRAY TO ANOTHER
3 7 5 9 6
13
STATEMENT EXECUTION
3 7 5 9 6
14
SUMMING AND AVERAGING
ARRAY ELEMENTS
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.
PROCESSING PARTIALLY-FILLED
ARRAYS
Sometimes you need to store a series of items in
an array, but you do not know the number of
items that there are.
E.g.taking a quiz in class
Don’t know in advance about the no of students
present
As a result, you do not know the exact number
of elements needed in the array
One solution is to make the array large enough to
hold the largest possible number of items.
PROCESSING PARTIALLY-FILLED
ARRAYS
This can lead to another problem, however if the
actual number of items stored in the array is less
than the number of elements
i.e. the array will be only partially filled.
When you process a partially filled array, you
must only process the elements that contain valid
data items
To deal with partially filled arrays, use a counter
variable to keep track of the number of valid items
stored in the array.
SAFE USE OF PARTIALLY FILLED
ARRAYS
const int SIZE = 100;
int numbers[SIZE];
int count = 0;
Each time we add an item to the array, we must increment count .
int num;
cout << "Enter a number or −1 to quit: ";
cin >> num;
55 60 80 -1
while (num != −1 && count < SIZE)
{
numbers[count] = num;
count++;
cout << "Enter a number or −1 to quit: "; Count=3
cin >> num;
0 1 2 …… 99
} 55 60 80 ……. ……
SAFE USE OF PARTIALLY FILLED
ARRAYS
Using the count to determine the maximum array subscript
to use.
0 1 2 …… 99
55 60 80 ……. ……
Count=3
int[] numbers = { 3, 6, 9 };
for (auto val : numbers)
cout << val << endl;
MODIFYING AN ARRAY WITH A RANGE-
BASED FOR LOOP
As the range-based for loop executes, its range variable
contains only a copy of an array element.