1D Arrays

Looping Constructs for One-Dimensional Arrays

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++) {
}
```

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.

Take a Study Break

Star Trek gets SEXY

Chris Pine and Zoe Saldana heat up the red carpet!

Are you afraid of relationships?

Auntie SparkNotes can help!

Sexy starlet style

See every single look from the Met Gala!

Geeky Actors: Then and Now

Travel back in time!

10 Movies Better Than Their Books

What do you think?

How To Look Like J-Law...

When you don't look like J-Law.

12 Scientific Inaccuracies in Into Darkness

What did Star Trek get wrong?

Villains We Want These Actresses to Play

From super cute to super bad!

The Book

Read What You Love, Anywhere You Like

Get Our FREE NOOK Reading Apps