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”.
| Position during body | Scores[1] | Scores[2] | Scores[3] | Scores[4] | Scores[5] |
|---|---|---|---|---|---|
| 1 | 0 | Unassigned | Unassigned | Unassigned | Unassigned |
| 2 | 0 | 0 | Unassigned | Unassigned | Unassigned |
| 3 | 0 | 0 | 0 | Unassigned | Unassigned |
| 4 | 0 | 0 | 0 | 0 | Unassigned |
| 5 | 0 | 0 | 0 | 0 | 0 |
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
| Position | Read score | Total after addition |
|---|---|---|
| 1 | 8 | 8 |
| 2 | 5 | 13 |
| 3 | 12 | 25 |
| 4 | 7 | 32 |
| 5 | 9 | 41 |
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 Count12 | 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 Position13 | 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.