Lesson 8 – Arrays

In this lesson, we shall learn a very important data structure that is very commonly used in programming. This data structure is called the array.

When you want to store many information that uses an index to keep track, an array is the data structure to use. Some examples are like storing telephone numbers, marks and grades.


Refer to the C++ documentation on array. There are a few ways to declare an array:

int foo[5]; // declare array with a storage of 5 elements
int foo[5] = {16, 2, 77, 40, 12071}; // declare array with 5 integers inside
int bar[5] = {10, 20, 30};
int baz[5] = {};
int foo[] = {16, 2, 77, 40, 12071}; // automatic resize of array to fit the elements

You can access an array element by using its index.

Using the example in the documentation:

// Program 8.1
#include <iostream>
using namespace std;
int foo [] = {16, 2, 77, 40, 12071};
int n, result=0;
int main ()
    for ( n=0 ; n<5 ; ++n )
        result += foo[n];
    cout << result;
    return 0;

Before you type the program, guess what this is going to do. After this, type and run the program. Did you get what was expected?

Characteristics of Arrays

Arrays are very powerful data structures that is widely used in programming. However beginners usually think that you can add elements whenever you want to. This is not the case. An array, once declared, cannot change its number of storage. In some modern programming languages, this limitation is removed such that the array can dynamically change its storage. However, C++ is not such a language.

In the next lesson, we shall discuss array’s more powerful cousin, the vector. For this lesson, let us use arrays to perform some useful operations.

Challenge 2

You are a teacher and you have 10 students. You want to keep all their test marks in an array and use it to calculate the average. Also print out the highest mark and lowest mark.

This challenge is equivalent to the IGCSE Computer Science syllabus requirement for programming.

Input: you will key in ten marks altogether.

Output: Console will print out the average, highest and lowest marks.