CIE IGCSE | 8.2.3.1 Read and Write Array Values Using Loops

Lesson objective

Use loops to initialise, input, output and update one-dimensional array elements, and trace totals and conditional counts with correct bounds.

Learn

8.2.3.1 | READ AND WRITE ARRAY VALUES USING LOOPS

01 | STOP WRITING THE SAME INSTRUCTION FIVE TIMES

A quiz records five scores. You could write INPUT Scores[1], INPUT Scores[2] and three more instructions. The task is the same each time; only the index changes.

A loop can repeat that task while an INTEGER counter supplies each index. Traversal means visiting array elements in a planned order. A loop body is the instruction or group of instructions repeated by the loop.

In this lesson Scores has bounds one to five and element type INTEGER. An array declaration provides the storage structure, but it does not automatically assign meaningful values to every element.

02 | MATCH THE COUNTER TO THE ARRAY BOUNDS

The declaration permits indices one through five inclusive. The FOR counter Position takes exactly those values, so every selected element is within bounds.

This first loop explicitly initialises every element to zero. Position identifies the destination, while the literal zero supplies the stored value. The counter does not become zero.

After the loop, all five elements contain assigned zeros. That result comes from the assignments in the loop, not from the declaration alone.

DECLARE Scores : ARRAY[1:5] OF INTEGER
DECLARE Position : INTEGER
FOR Position ← 1 TO 5
  Scores[Position] ← 0
NEXT Position

03 | TRACE EACH WRITE

Each iteration reaches a different assignment destination. At Position one, Scores[1] receives zero. At Position two, Scores[2] receives zero, and so on.

The trace below records the array after each assignment. “Unassigned” means this algorithm has not yet supplied a value there; it does not mean the element contains the STRING “Unassigned”.

The counter selects where the assignment stores its value
Position during bodyScores[1]Scores[2]Scores[3]Scores[4]Scores[5]
10UnassignedUnassignedUnassignedUnassigned
200UnassignedUnassignedUnassigned
3000UnassignedUnassigned
40000Unassigned
500000

04 | RECEIVE A DIFFERENT VALUE FOR EACH ELEMENT

To store user-supplied scores, replace the zero assignment with INPUT Scores[Position]. Each execution receives another value and writes it into the current element.

The prompt includes Position so the user knows which score is being requested. If the inputs are eight, five, twelve, seven and nine, those values fill indices one to five in that order.

This example assumes each input is a valid INTEGER score. INPUT stores a value; it does not automatically enforce every application rule.

FOR Position ← 1 TO 5
  OUTPUT "Enter score for player ", Position
  INPUT Scores[Position]
NEXT Position

05 | OUTPUT A VALUE FROM EVERY ELEMENT

After the array has been filled, another loop can read it. The same counter range selects the same five positions, but OUTPUT reads rather than writes.

With scores eight, five, twelve, seven and nine, those values are displayed in order. Reading does not remove them from the array or replace them with the counter values.

Input and output loops have different jobs. An output loop cannot fill elements that have never been assigned.

FOR Position ← 1 TO 5
  OUTPUT "Player ", Position, " score: ", Scores[Position]
NEXT Position

06 | RUN A COMPLETE INPUT-THEN-OUTPUT PROGRAM

Both loops use Position, but each FOR starts its own sequence at one. The second loop does not depend on a particular counter value left after the first finishes.

The program receives all five scores before it displays the stored collection. Reusing one counter for separate sequential loops is different from using the same counter for two nested active loops.

DECLARE Scores : ARRAY[1:5] OF INTEGER
DECLARE Position : INTEGER
FOR Position ← 1 TO 5
  OUTPUT "Enter score ", Position
  INPUT Scores[Position]
NEXT Position
FOR Position ← 1 TO 5
  OUTPUT "Stored score ", Position, ": ", Scores[Position]
NEXT Position

07 | UPDATE EACH STORED VALUE

Suppose every player receives two bonus points. Scores[Position] ← Scores[Position] + 2 reads the current selected score, adds two and writes the result back into that same element.

The index does not increase because of this assignment; the FOR loop controls its next value. Only the selected score changes during each body execution.

Starting with eight, five, twelve, seven and nine, the final values are ten, seven, fourteen, nine and eleven. Running the bonus loop a second time would add another two to each current value.

FOR Position ← 1 TO 5
  Scores[Position] ← Scores[Position] + 2
NEXT Position

08 | STEP THROUGH WRITES, READS AND UPDATES

Choose a task and follow one array element per step. Fill stores the example values. Read displays them. Add bonus reads and replaces each score, and total adds each score into a separate running total.

    We use Total ← Total + Scores[Position] because we want to keep the total so far and add the next score to it. Total starts at zero and grows as each score is added. Assigning just the new score would replace the total and lose the earlier scores. Each task resets to its stated starting state. Fill begins with unassigned elements and uses five predetermined valid inputs. The other tasks begin with all example scores assigned. This makes each trace independent.

    09 | TOTAL THE VALUES, NOT THEIR INDICES

    A running total accumulates the values processed so far. Initialise Total once before the loop, then add the selected score on every iteration.

    The example scores sum to forty-one. Adding Position instead would give one plus two plus three plus four plus five, or fifteen: that totals positions rather than scores.

    The array is unchanged by this calculation because the assignment target is Total. The mean is Total / 5, which is 8.2, so a variable holding it should be REAL.

    DECLARE Total : INTEGER
    DECLARE Average : REAL
    Total ← 0
    FOR Position ← 1 TO 5
      Total ← Total + Scores[Position]
    NEXT Position
    Average ← Total / 5
    OUTPUT Total
    OUTPUT Average
    The total grows from one iteration to the next
    PositionRead scoreTotal after addition
    188
    2513
    31225
    4732
    5941

    10 | KEEP INITIALISATION AT THE RIGHT LEVEL

    If Total ← 0 is placed inside the loop, earlier additions are discarded each time. The final result becomes only the last score, nine, rather than forty-one.

    When the aim is a total across the whole array, initialise before FOR and output after NEXT. An output inside the loop can deliberately show partial totals, but it is a different requirement.

    Changing code placement changes behaviour. Indentation and tracing help show which instructions run once and which run on every iteration.

    11 | COUNT VALUES MEETING A CONDITION

    To count scores at least eight, use a separate Count variable. The loop visits every position, while an IF decides whether that value contributes to the count.

    Eight, twelve and nine qualify, so Count finishes at three. Count increases by one per qualifying element, not by the score value and not by Position.

    The inclusive comparison accepts eight. A condition using greater than eight would count only twelve and nine.

    DECLARE Count : INTEGER
    Count ← 0
    FOR Position ← 1 TO 5
      IF Scores[Position] >= 8
        THEN
          Count ← Count + 1
      ENDIF
    NEXT Position
    OUTPUT Count

    12 | VALIDATE EACH INPUT BEFORE ADVANCING

    A score system may permit only INTEGER values from zero to twenty. An inner REPEAT loop can retry the current element until its value is in that range.

    The outer Position advances only after the current element passes the check. With inputs twenty-five, eight, five, twelve, seven and nine, the first position is attempted twice and the remaining four once: six inputs produce five accepted scores.

    This example assumes inputs are INTEGER values. The range check does not convert arbitrary text. An invalid attempted value is stored temporarily in the current element and replaced by the next attempt before the algorithm moves on.

    FOR Position ← 1 TO 5
      REPEAT
        OUTPUT "Enter score from 0 to 20 for player ", Position
        INPUT Scores[Position]
      UNTIL (Scores[Position] >= 0) AND (Scores[Position] <= 20)
    NEXT Position

    13 | CHECK FOR MISSING OR EXTRA VISITS

    For ARRAY[1:5], FOR Position ← 1 TO 4 misses the final element. FOR Position ← 1 TO 6 attempts one out-of-bounds access. A zero-based ARRAY[0:4] instead needs zero through four to visit its five elements.

    An off-by-one error occurs when a limit or count is one too high or too low. Match the loop to the actual declared indices, not just the number of elements.

    A loop traversing a selected part of an array may deliberately use smaller bounds. State that intention so a partial traversal is not mistaken for an accidental omission.

    14 | COPYING INTO ANOTHER ARRAY

    A loop can read one array and write another. Backup has the same bounds and element type as Scores, so each corresponding destination can receive the source’s current value.

    After this loop, changing Scores[1] does not automatically change Backup[1]. Each assignment copied an INTEGER value rather than creating a live link.

    Before copying, ensure source elements are assigned and both arrays permit every accessed index. An array of a different size needs a carefully chosen copying range.

    DECLARE Backup : ARRAY[1:5] OF INTEGER
    FOR Position ← 1 TO 5
      Backup[Position] ← Scores[Position]
    NEXT Position

    15 | PLAN THE LOOP’S JOB

    Decide whether each iteration should read, write or both. Match its counter range to the declared bounds. Initialise whole-task totals before the loop and place final outputs after it.

    A useful explanation is: “Position takes each valid index from one to five. INPUT writes one score at the selected position, therefore five accepted inputs fill the five elements.”

    Keep indices separate from stored values, and do not read an unassigned element. When retrying input, let the current value become valid before advancing the outer counter.

    The next lesson applies nested loops to two-dimensional arrays.

    MATCH THE ARRAY LOOP TASK

    Terminology

    Terminology

    Traversal

    Visiting array elements in a planned order.

    Loop body

    The instructions repeated by a loop.

    Loop counter

    The variable holding the current controlled repetition value.

    Index

    The INTEGER selecting an array position.

    Element read

    Retrieving the current value at an indexed position.

    Element write

    Storing a value at an indexed position.

    Initialisation

    Assigning starting values before they are needed.

    Bounds

    The permitted lowest and highest indices.

    FOR loop

    A count-controlled loop using a specified sequence of values.

    Running total

    An accumulator updated by adding each relevant value.

    Conditional count

    A count increased only for elements meeting a condition.

    Mean

    The total divided by the number of contributing values.

    Off-by-one error

    A boundary or count one too high or low.

    Validation loop

    A loop retrying input until the required check passes.

    Accepted input

    A supplied value that has passed the specified checks.

    Partial traversal

    A deliberate visit to only a selected part of an array.

    Array copy

    Assignments copying source values into corresponding destination elements.

    Final output

    An output after processing has completed, rather than an intermediate result.

    Questions

    Questions

    CHECK YOUR UNDERSTANDING

    Select all correct choices. Each exact set earns one point.

    1. Which are valid jobs for a loop over an array?
    2. Which visits every element of ARRAY[1:5] exactly once?
    3. INPUT Scores[Position] does which?
    4. Scores are 8, 5, 12, 7, 9. Which are correct?
    5. Where should a whole-array total be initialised?
    6. Adding two to every example score gives which?
    7. Which scores qualify for >= 8?
    8. Which apply to an inner validation loop?

    EXPLAIN AND COMPARE

    Write your answers before revealing each sample.

    1. Explain how a counter lets one INPUT instruction fill five elements.

    2. Compare a reading loop with a writing loop.

    3. Trace the running total for 8, 5, 12, 7, 9.

    4. Explain why Total ← 0 inside the loop gives the wrong whole-array sum.

    5. Calculate the mean of the example scores and suggest a suitable type.

    6. Describe a loop to count scores at least eight.

    7. Explain how validation changes input attempts without changing the number of accepted elements.

    8. Explain why loop limits must match indices rather than just array length.

    BUILD IT | FOUR WEEKLY READINGS

    Declare Readings : ARRAY[1:4] OF REAL. Use a loop to receive four valid REAL values, then another loop to output each value and calculate their total. Output the total and mean after the loop. Test 2.5, 0.0, -1.0 and 4.5. Initialise the total in the correct place and preserve the stored readings.

    Reveal one possible solution
    DECLARE Readings : ARRAY[1:4] OF REAL
    DECLARE Position : INTEGER
    DECLARE Total : REAL
    DECLARE Average : REAL
    FOR Position ← 1 TO 4
      OUTPUT "Enter reading ", Position
      INPUT Readings[Position]
    NEXT Position
    Total ← 0.0
    FOR Position ← 1 TO 4
      OUTPUT Readings[Position]
      Total ← Total + Readings[Position]
    NEXT Position
    Average ← Total / 4
    OUTPUT "Total: ", Total
    OUTPUT "Mean: ", Average

    The total is six and the mean is 1.5. The second loop reads each element but does not assign to it, so all four readings remain stored unchanged. Zero and negative readings still contribute as valid values in this scenario; it assumes suitable REAL inputs.

    Flashcards

    Flashcards

    Click to flip. Select the ideas you need to revisit.

    0 cards selected for revision.

      Selections are kept while this page is open.

      Workbook

      Workbook

      COMING SOON

      The workbook for 8.2.3.1 Read and Write Array Values Using Loops is coming soon. Complete the matching task and written questions in your exercise book.