Array Patterns
Array Patterns
Array Patterns: Here are some common patterns that use arrays. In all the examples,
assume that the array is called blah; that it has length given by the variable length; and that the
array holds numbers, except where indicated.
Follow the link to go straight to that pattern.
1. Accessing the kth element of the array, for a given k. Just use:
blah[k]
2. Printing (or otherwise processing) all the values of an array, from beginning to end.
Must begin at 0.
Must be < (not <=).
int k;
Many of the following patterns are special cases or variations of this general “processing”
pattern.
4. Counting the number of elements in the array that meet a given condition.
To sum just the elements that meet a given condition, use an if as in the counting example
above.
Arrays Page 4
int k;
Start by setting indexOfElement
int indexOfElement = -1; to an impossible value.
Break out
for (k = 0; k < length; ++k) {
of the loop
if you find if (blah[k] == whatYouAreLookingFor) {
what you indexOfElement = k;
want. break; The condition (what is inside the if clause) will vary
} from problem to problem. This example finds the
} first element that equals whatYouAreLookingFor.
int k;
b. Initializing the elements of an
int length = 400;
array to values that are a function
int squares[length];
of the index.
For example, you can set the kth entry for (k = 0; k < length; ++k) {
of a squares array to k2, as in the example
squares[k] = k * k;
to the right:
}
c. Initializing the elements of an array to values input by the user (or from a file),
asking the user how big the array should be.
int length, k;
d. Initializing the elements of an array to values input by the user (or from a file),
with a sentinel loop.
numbers[actualLength] = number;
After breaking out of the loop, the array
++ actualLength;
contains the numbers that the user
}
inputted. The variable actualLength
holds the number of inputs, hence is
treated as the length of the array in the
subsequent code.
This version of this pattern chooses an array length that the programmer hopes will
be “big enough” in practice. This is not a very robust solution! A better (but more
complicated) solution would be to use pointers to simulate the array and
dynamically (i.e., at run-time) “grow” the array as needed using malloc or realloc –
see How to Use Pointers to Save Time and Space.
Arrays Page 7
9. Patterns that refer to another element while processing the current element.
The pattern above for “finding the largest (or smallest) number in an array of numbers” is
an example of this pattern – the pattern loops through the array from beginning to end, and
at each iteration compares the current element (blah[k]) to the largest element found so
far (blah[indexOfLargest]).
Another example of this pattern is the int k; Start by setting isSorted
code to the right, which determines int isSorted = 1; to 1 (which means “true”).
whether an array is sorted from
smallest to largest. It does so by looping
for (k = 0; k < length - 1; ++k) {
through the array from beginning to end,
if (blah[k] > blah[k+1]) {
comparing the current element to the
next element in the array. isSorted = 0;
break;
After the loop concludes, if isSorted is still 1 (true), then } Here we have
every element of the array is no bigger than the } found a pair of
element after it, so the array is sorted from smallest to elements that are
largest. Do whatever the problem calls for in that case. NOT in the right
if (isSorted == 1) {
order, so set
... isSorted to 0
Otherwise, the loop found an element of the array } else { (“false”) and quit
that is smaller than the element after it, so the array ... the loop.
is NOT perfectly sorted from smallest to largest. Do }
whatever the problem calls for in that case.
The best way to avoid such “off by 1” errors is to trace the code on one or more small,
concrete examples. For example, here you should try arrays of length 4 and 5. (You should
do both odd and even lengths because of the length / 2 in the for statement.)
Arrays Page 8
Another classic example of the loop-within-a-loop pattern is selection sort, an algorithm for
sorting an array. Selection sort is simple to understand/code and a good example of a loop-
within-a-loop pattern. However, be aware that there are much faster sorting algorithms
(e.g. quicksort) and that the standard C library includes a sort function (qsort).
int j, k, indexOfMinimum;
float temp;
Repeatedly:
So the first time through the outer loop, you put the
smallest element into blah[0]. The second time
through the outer loop, you put the second-smallest
element into blah[1]. And so forth.
Arrays Page 9
leftIndex = 0;
Try the middle of the
rightIndex = length - 1;
portion of the array
that might hold the
while (leftIndex < rightIndex) { numberToFind.
middleIndex = (leftIndex + rightIndex) / 2;
} else {
return middleIndex;
Likewise, but we can restrict our
}
search to array positions smaller
} than middleIndex in this case.
return -1;
} The number at middleIndex is
We have eliminated all positions in the numberToFind – found it!
array – numberToFind is not in the
array. Return a code to indicate that.
Arrays Page 10
12. The “histogram pattern” for counting the occurrences of “events”, e.g. to find the mode
(most common number) of an array.
This pattern is useful whenever you want to know how often an “event” occurs, when you
have a collection of events that can be numbered into a relatively small range. The general
pattern goes like this:
Step 1: Declare an array that will hold values 0 .. n, where “events” are numbered
and n is the biggest event that can occur.
Step 2: Initialize all elements of the array to 0.
Step 3: Repeatedly:
o Get the next “event” in the collection of events from which the histogram is
to be built. That event’s number is, say, m.
o Increment the array value at index m.
After Step 3 completes, the array holds the desired histogram – the value at index i is
the number of times that event i occurred (hence the array is a histogram).
Here is a concrete example of this pattern: Suppose that you generate 10,000 random
integers, each between 0 and 100, inclusive, and suppose that you want to know which
random integer occurred most often. The following code solves this problem.