Skip over navigation

1D Arrays

Looping Constructs for One-Dimensional Arrays

Problems and Solutions 1

Problems and Solutions 2

Arrays are very easily used with looping constructs. This is due to the fact that each location in the array has a number associated with it and that these numbers increase by 1 from one element to the next. In this section, we will introduce a few of the looping idioms commonly associated with arrays.

The simplest way to loop through all of the elements in an array is to have a counter that starts with the initial value of zero (the index of the first location in the array) and increments by one until it has the value of the last location in the array (one less than the number of elements in the array). For example, imagine we have an array of grades, an integer counter, and a sharp-defined constant that holds the number of grades in the array. If we want to determine what the average grade is, we might use a loop as follows:


for (i = 0, total = 0; i < NUM_GRADES; i++) {
	total += grades[i];
}
average = total / NUM_GRADES;

This loop accesses each location in the array exactly once and adds the value at that location into a variable which is summing the total. The average of all of the values in the array is then calculated by dividing this total by the number of cells in the array. A similar loop can be used in many cases in which you want to go through all of the elements in the array.

Follow Us