Unit 2 · Lesson 124 minAcademic review pending

One name, many values: arrays

Store and process a fixed-size sequence safely with indexes, loops, and accumulators.

Choose explanation

After this lesson

You should be able to

  • Declare, initialize, traverse, and update a one-dimensional array.
  • Prevent out-of-bounds access by reasoning about valid indexes.
01

Indexes are positions, not counts

An array stores elements of one type in consecutive positions. int marks[5] has five elements, but its valid indexes are 0 through 4. C does not automatically stop an invalid index, so the program must maintain the boundary.

Keep the element count close to the array and use i < count. Writing i <= count reaches one position beyond the end. That single character difference is a common memory bug.

Average an array
int marks[] = {72, 81, 65, 90, 77};
size_t count = sizeof marks / sizeof marks[0];
int total = 0;

for (size_t i = 0; i < count; i++) {
    total += marks[i];
}

double average = (double) total / count;
02

Separate traversal from the result

Most array algorithms combine a traversal with state: total for a sum, currentMax for a maximum, or foundIndex for a search. State the invariant—what the state means after processing indexes 0 through i.

For a maximum, initialize from the first element rather than an arbitrary value such as zero. Zero fails when every value is negative. Also handle an empty logical array before reading element zero.

Try it yourself

Find the smallest value and its first index in an integer array.

Need a hint?

Initialize both the value and index from element zero, then scan from index one.

Check the worked solution

Update min and minIndex only when a strictly smaller value appears; equality then preserves the first index.

int min = values[0];
size_t minIndex = 0;

for (size_t i = 1; i < count; i++) {
    if (values[i] < min) {
        min = values[i];
        minIndex = i;
    }
}

Quick check

What is the last valid index of int a[8]?

Select an answer to check your thinking.

Why this lesson exists

Syllabus mapping

One-dimensional arrays

Maps to course outcomes CO3, CO5.