Study Guide

Arrays

How a program stores a list of values under one name: declaring one-dimensional and two-dimensional arrays, using an index (including a variable as the index), and reading and writing every element with loops, with nested loops for a table of values.

Lesson 5.10 Algorithms and Programming

For: Cambridge IGCSE Computer Science learners, or Key Stage 3 learners who have met loops and selection (about ages 13 to 14)

Stage: Think

A row of lockers

A school corridor has a row of 30 lockers. Each one has a number painted on its door. A fictional new pupil is told “your locker is number 17”.

Think it through

Why is it better for the lockers to share one description (“locker”) with a number on each, than for every locker to have an unrelated name such as Maple, Otter or Jupiter? Think about telling a new pupil, and about checking every locker at the end of term.

Show a model answer

One shared name plus a number says exactly which locker is meant, and the numbers run in order, so someone can check “locker 1, locker 2, locker 3…” without missing one. With unrelated names there is no order to follow and nothing to count. A program that stores 30 scores has the same problem and the same solution.

Stage: Discover

Storing a list under one name

Think it through

A fictional quiz has five players, and the program must remember each player’s score until the end. With ordinary variables you would need Score1, Score2, Score3, Score4 and Score5. What goes wrong if there are 500 players, and what would you like to be able to write instead?

Show a model answer

You would have to write 500 variable names, and a loop cannot go through Score1, Score2 and so on, because each name is a different variable. It would be better to have one name for the whole list, and a number to say which one is meant, like the lockers.

An array stores a fixed number of values, all of the same data type, under one name. Each value is an element. The place of an element is its index, a whole number written in square brackets after the name. A list of this kind is a one-dimensional array, because one number is enough to find any element.

DECLARE Scores : ARRAY[1:5] OF INTEGER
Scores[1] ← 12
Scores[2] ← 7
Scores[3] ← 15
Scores[4] ← 9
Scores[5] ← 13

ARRAY[1:5] gives the bounds: the lowest index is 1 (the lower bound) and the highest is 5 (the upper bound), so there are five elements. OF INTEGER says what each element holds. The array’s size is fixed when it is declared. Writing a value is an assignment to one element; reading it is using Scores[3] in an expression, so OUTPUT Scores[3] outputs 15.

Because the index can be any expression that gives a whole number, a variable can be the index: if Position is 2, then Scores[Position + 1] is Scores[3].

Working out expressions that use the Scores array
ExpressionValue
Scores[3]15
Scores[1] + Scores[2]
Scores[5] - Scores[4]
Scores[Position + 1] when Position is 2

    Show the completed table
    ExpressionValue
    Scores[3]15
    Scores[1] + Scores[2]19
    Scores[5] - Scores[4]4
    Scores[Position + 1] when Position is 215

    The first row is given as an example.

    An index and the value stored there are different things. In Scores[3] the 3 is the index, the place; the value at that place is 15. Players’ scores change while the places stay the same.

    Check your understanding

    Scores is declared ARRAY[1:5] OF INTEGER. Which statement refers to an element that does not exist?
    Show the answer

    Answer: B. Scores[6] ← 4

    An index must lie between the lower and the upper bound.

    The first index can be 0 or 1: ARRAY[0:4] OF INTEGER also holds five elements, but they are numbered 0 to 4. Cambridge pseudocode usually uses 1, and the declaration always states which, so read it before using the array.

    Stage: Predict

    Filling and adding up an array

    A loop and an index work together: the loop variable counts the positions, and the array element at that position is read or written. A fictional quiz program reads five scores and then totals them.

    DECLARE Scores : ARRAY[1:5] OF INTEGER
    DECLARE Total : INTEGER
    Total ← 0
    FOR Position ← 1 TO 5
      OUTPUT "Score for player ", Position
      INPUT Scores[Position]
    NEXT Position
    FOR Position ← 1 TO 5
      Total ← Total + Scores[Position]
    NEXT Position
    OUTPUT "Total: ", Total

    Think it through

    The scores typed are 12, 7, 15, 9 and 13. Predict the output. Why does the program need two loops, rather than adding each score to Total as it is typed?

    Show what happens

    It outputs Total: 56. One loop would be enough for the total alone, but the array keeps all five scores after the first loop, so they can be used again, to find the highest, to show them or to compare them. A running total alone would forget each score as soon as it was added.

    Follow the first loop and watch the array fill up. Each row shows the array after that pass; cells not yet written are empty.

    Following the array while the scores are typed
    PassScore typedScores[1]Scores[2]Scores[3]Scores[4]Scores[5]
    Position 112
    Position 2712
    Position 315127
    Position 4912715
    Position 513127159

      Show the completed table
      PassScore typedScores[1]Scores[2]Scores[3]Scores[4]Scores[5]
      Position 11212
      Position 27127
      Position 31512715
      Position 49127159
      Position 51312715913

      The elements already written keep their values; each pass writes one new one.

      The array holds 12, 7, 15, 9 and 13. The aim is to output the highest score and the position of the player who got it.

      1. Start with the first element. As in Lesson 6, begin with the first value as the highest so far: Highest ← Scores[1]. The player who holds it is number 1, so BestPosition ← 1.
      2. Look at the rest. The loop starts at position 2, because position 1 has already been dealt with.
      3. Replace when something is higher. If Scores[Position] > Highest, a new highest has been found, so both Highest and BestPosition are updated. The position is what the loop variable holds at that moment.
      4. Output after the loop.
      Highest ← Scores[1]
      BestPosition ← 1
      FOR Position ← 2 TO 5
        IF Scores[Position] > Highest
          THEN
            Highest ← Scores[Position]
            BestPosition ← Position
        ENDIF
      NEXT Position
      OUTPUT "Highest: ", Highest
      OUTPUT "Player: ", BestPosition

      At Position 2 the score 7 is not higher than 12. At Position 3 the score 15 is higher, so Highest is 15 and BestPosition is 3. The scores 9 and 13 are not higher. The program outputs Highest: 15 and Player: 3.

      Following the highest-score program for the scores 12, 7, 15, 9 and 13
      PositionScores[Position]Scores[Position] > Highest ?HighestBestPosition
      Before the loop--121
      27No121
      315Yes153
      49
      513

        Show the completed table
        PositionScores[Position]Scores[Position] > Highest ?HighestBestPosition
        Before the loop--121
        27No121
        315Yes153
        49No153
        513No153

        The first three rows are given; the other rows are for you.

        Check your understanding

        At the end of the program, what does BestPosition hold?
        Show the answer

        Answer: A. 3, the position in the array of the highest score.

        Store the index when you need to know where, and the value when you need to know what.

        Stage: Discover

        A table of values

        A fictional cinema’s screen has three rows of four seats, and the booking program must remember which seats are taken.

        Think it through

        A ticket says “Row 2, seat 3”. How many numbers do you need to pick out one seat? Why would a single number, as in the lockers, be awkward for a seating plan?

        Show a model answer

        Two numbers are needed, a row and a seat in that row. A single number from 1 to 12 would work for the computer, but people read the plan as rows and seats, and the program is easier to write when the row and the seat are separate numbers.

        An array whose elements are found with two indexes is a two-dimensional array, like a table with rows and columns. The first index is the row and the second is the column. Each dimension has its own bounds.

        DECLARE Seats : ARRAY[1:3, 1:4] OF STRING

        This declares three rows (1 to 3) of four seats (1 to 4), twelve elements in all. Each element holds “F” for free or “X” for taken. After three seats are booked, the plan looks like this:

        Seat 1Seat 2Seat 3Seat 4
        Row 1XFFF
        Row 2FFXF
        Row 3FFFX

        Seats[2, 3] is the element in row 2 and seat 3, which holds “X”.

        Reading the seating plan above
        ExpressionValue
        Seats[2, 3]X
        Seats[2, 2]
        Seats[3, 4]
        Seats[1, 4]

          Show the completed table
          ExpressionValue
          Seats[2, 3]X
          Seats[2, 2]F
          Seats[3, 4]X
          Seats[1, 4]F

          The first row is given as an example.

          Apply it

          The plan is declared ARRAY[1:3, 1:4]. A programmer wants the last seat in row 1 and writes Seats[4, 1]. What is wrong?
          Show the answer

          Answer: D. The row comes first, so it is Seats[1, 4]; there is no row 4.

          Always name the row first, then the column, in the order of the declaration.

          Stage: Explain

          Visiting every seat

          The booking program starts a new evening by setting every seat to “F”, for free.

          Think it through

          A single FOR loop counts one number. The plan has rows and seats. How could loops be arranged so that every one of the twelve seats is visited exactly once?

          Show a model answer

          One loop can go through the rows, and for each row a second loop can go through the seats in it, like reading each word of each line in turn. Every seat is reached once, because every row is visited and every seat of each row is visited.

          To visit every element of a two-dimensional array, the program needs nested iteration: an outer loop for the rows and an inner loop for the seats in each row. For each pass of the outer loop, the inner loop runs through all of its values.

          FOR Row ← 1 TO 3
            FOR Seat ← 1 TO 4
              Seats[Row, Seat] ← "F"
            NEXT Seat
          NEXT Row

          This sets all twelve seats to “F”: the outer loop picks a row, and the inner loop sets each seat in it. Each loop ends with its own NEXT, the inner one first.

          1. State the job. Count how many seats hold “X”. That is a count, so set it to 0 before the loops.
          2. Choose the loops. Every row and every seat must be looked at: rows 1 to 3 in the outer loop, seats 1 to 4 in the inner loop.
          3. Test each element. Inside the inner loop, Seats[Row, Seat] = "X" tests the seat that the two loop variables point to, and 1 is added to Booked when it is true.
          4. Output after both loops are finished.
          Booked ← 0
          FOR Row ← 1 TO 3
            FOR Seat ← 1 TO 4
              IF Seats[Row, Seat] = "X"
                THEN
                  Booked ← Booked + 1
              ENDIF
            NEXT Seat
          NEXT Row
          OUTPUT "Booked: ", Booked

          For the plan above each row contains exactly one X, so Booked is 1 after row 1, 2 after row 2 and 3 after row 3, and the program outputs Booked: 3.

          Following the seat count, one row of the plan at a time
          RowSeats checkedX found in this rowBooked after this row
          141
          2
          3

            Show the completed table
            RowSeats checkedX found in this rowBooked after this row
            1411
            2412
            3413

            The first row is given as an example.

            Check your understanding

            In the counting program, how many times in total is the line IF Seats[Row, Seat] = “X” carried out?
            Show the answer

            Answer: C. 12, because the inner loop runs 4 times for each of the 3 rows.

            The inner loop is completed in full for each pass of the outer loop, so the numbers of passes multiply.

            Stage: Apply

            Spot the mistake

            Sam (fictional) wants the total of five marks that have been read into an array.

            DECLARE Marks : ARRAY[1:5] OF INTEGER
            FOR Position ← 1 TO 5
              INPUT Marks[Position]
            NEXT Position
            Total ← 0
            FOR Position ← 1 TO 6
              Total ← Total + Marks[Position]
            NEXT Position
            OUTPUT Total

            Apply it

            The program stops with an error after adding the fifth mark. What is the fault and the fix?
            Show the answer

            Answer: A. The second loop goes to 6, but there is no element 6; it should end at 5.

            A loop through an array must stay inside its bounds: use the array’s own bounds as the loop’s start and end.

            Stage: Apply

            Write one yourself

            A fictional library keeps the number of times each of six books was borrowed this term, in an array called Borrowed. A book borrowed more than 10 times is popular.

            Think it through

            Write pseudocode that declares the array, reads the six values into it with a loop, and then outputs the total number of loans and the number of popular books. What does it output for the values 14, 3, 11, 10, 22 and 8?

            Show a model answer
            DECLARE Borrowed : ARRAY[1:6] OF INTEGER
            Total ← 0
            Popular ← 0
            FOR Book ← 1 TO 6
              OUTPUT "Loans for book ", Book
              INPUT Borrowed[Book]
            NEXT Book
            FOR Book ← 1 TO 6
              Total ← Total + Borrowed[Book]
              IF Borrowed[Book] > 10
                THEN
                  Popular ← Popular + 1
              ENDIF
            NEXT Book
            OUTPUT "Total loans: ", Total
            OUTPUT "Popular books: ", Popular

            The values add up to 68 (14 + 3 + 11 + 10 + 22 + 8) and three are above 10 (14, 11 and 22), so the program outputs Total loans: 68 and Popular books: 3. The 10 is not above 10, so it is not counted.

            Go deeper The same ideas in Python
            scores = [12, 7, 15, 9, 13]
            print(scores[2])
            
            total = 0
            for score in scores:
                total = total + score
            print(total)
            
            seats = [["F"] * 4 for row in range(3)]
            seats[0][0] = "X"
            seats[1][2] = "X"
            seats[2][3] = "X"
            
            booked = 0
            for row in range(3):
                for seat in range(4):
                    if seats[row][seat] == "X":
                        booked = booked + 1
            print(booked)
            • Python’s nearest thing to an array is a list, written with square brackets. A list does not have a fixed size, but the programs here do not need it to change.
            • Python counts from 0, so Scores[3] in the pseudocode is scores[2]. The first element is scores[0], and the last is scores[len(scores) - 1].
            • A two-dimensional array is a list of lists: seats[1][2] is row 2, seat 3 counting from 1, as in Seats[2, 3].
            • Use [["F"] * 4 for row in range(3)] to build the grid. Writing [["F"] * 4] * 3 would make three names for one row, so booking one seat would book it in every row.
            • This program prints 15, then 56, then 3.

            Stage: Consolidate

            Show what you know

            Think it through

            Explain to a friend what an array is, how it differs from a set of separate variables, and when a program needs a two-dimensional one. Use a school example of your own.

            Show a model answer

            A good answer says an array stores a fixed number of values of the same type under one name, each found by its index, so a loop can work through them, which a set of separate variables does not allow. It says a two-dimensional array is for data that is laid out in rows and columns, such as a seating plan, a timetable or a table of pupils and test marks, where two indexes are needed.

            Apply it

            Scores is declared ARRAY[1:4, 1:3] OF INTEGER. It holds the three test marks (columns 1 to 3) of four pupils (rows 1 to 4). Which loop adds up the three test marks of pupil 2, with Total starting at 0?
            Show the answer

            Answer: B. FOR Test ← 1 TO 3: Total ← Total + Scores[2, Test]

            Fix the index that picks the row you are interested in, and let a loop move through the other.

            • An array holds a fixed number of values of one data type under one name. Each element is found by its index: DECLARE Scores : ARRAY[1:5] OF INTEGER, then Scores[3].
            • The declaration gives the bounds. The first index may be 0 or 1; stay within the bounds, because an index outside them is an error.
            • The index can be a variable or an expression, so a FOR loop can read or write every element: Scores[Position].
            • A two-dimensional array has two indexes, row first and then column, and is declared with ARRAY[1:3, 1:4]. Nested loops visit every element; the passes multiply, so 3 rows of 4 seats is 12 passes.
            • Usual faults: an index of 0 or one past the end, the row and column the wrong way round, and confusing the index with the value stored there.

            Sources and scope

            • What this lesson is. The tenth lesson of the Algorithms and Programming module, written for this site. It covers point 8.2 of Cambridge IGCSE Computer Science 0478 (2026 to 2028, version 6): one-dimensional and two-dimensional arrays, with the use of loops, variables as indexes and nested iteration. Its curriculum links are provisional and imply no review or endorsement by any examination board.
            • Original material. The lockers, the quiz, the cinema, the library and Sam are fictional, written for this lesson. The declarations follow the syllabus’s pseudocode guide, and every output was worked out by hand and checked with an equivalent Python program.
            • Simplified on purpose. Arrays are shown with a lower bound of 1, as the guide generally does, with a note on zero. Only whole-number indexes are used. Arrays of records and arrays passed to subroutines are not taught. Two-dimensional arrays are shown only as rows and columns.
            • Left to other lessons. Searching an array and sorting it are in Lesson 11; storing an array in a file is not taught here.