Chapter 3

Arrays and Data Structures

Understand how a one-dimensional array stores same-type values under one name, indexed from 0, and how a loop visits every element.

What is an array?

An array is a data structure that stores many values of the same type under one name. Instead of using ten separate variables for ten marks, you use one array of ten elements. Each element is reached by its index (its position number).

Key idea

In most programming languages a one-dimensional array is indexed from 0. So an array of size 5 has valid indexes 0, 1, 2, 3, 4 - the last index is size − 1.

Using elements

You read or change one element by writing its index in brackets. If mark is an array, mark[0] is the first element and mark[4] is the fifth. Notice that the index is always one less than the counting position, because indexing starts at 0. Writing to an element, such as mark[2] = 80, changes just that one value and leaves the rest untouched.

Example

Given score = [90, 75, 60, 88]: score[0] is 90, score[2] is 60, and the array has 4 elements so the highest valid index is 3. Using score[4] would be an error (index out of range).

Why arrays help

Because elements share one name and are numbered, a loop can visit every element easily - for example adding all the marks by stepping the index from 0 to size − 1. This makes arrays ideal for lists of data such as marks, names or temperatures.

Remember

  • All elements of an array have the same data type.
  • Indexing usually starts at 0; the last index = size − 1.
  • An index outside the range causes an out-of-range error.

Stuck on this topic? A verified JomKelas tutor can walk you through it.

Find a verified tutor