Grade 11 · One-dimensional arrays · Lesson and coding task · about 14 minutes
Open this task in the Delphi workspace →
Almost every array question in the NSC boils down to three patterns. Learn them as reflexes:
1. Total & average — a running total over the array:
iTotal := 0;
for i := 1 to 5 do
iTotal := iTotal + arrMarks[i];
rAvg := iTotal / 5;
2. Highest (or lowest) — assume the first is the best, then challenge it:
iHigh := arrMarks[1];
iPos := 1;
for i := 2 to 5 do
if arrMarks[i] > iHigh then
begin
iHigh := arrMarks[i];
iPos := i; // remember WHERE - parallel arrays!
end;
3. Search — you will meet it in the next lesson.
Keeping the position (iPos) is the crucial habit: it lets you look up the matching name in the parallel array.
What you will do
- Memo line 1: Total: 313
- Memo line 2: Average: 62.6 (one decimal)
- Memo line 3: Top learner: Anele (90)
Hints
- Total first: start at 0, add arrMarks[i] each lap. The average is iTotal / 5 (a Real!).
- For the highest: start with arrMarks[1] as champion and let 2..5 challenge it. Store the winning index in iPos.
- FloatToStrF(rAvg, ffFixed, 8, 1) gives the average with one decimal. The top line uses arrNames[iPos].
Model solution
const
arrNames : array[1..5] of String = ('Thabo', 'Lerato', 'Anele', 'Sipho', 'Zanele');
arrMarks : array[1..5] of Integer = (78, 45, 90, 33, 67);
procedure TfrmStats.btnStatsClick(Sender: TObject);
var
i, iTotal, iHigh, iPos : Integer;
rAvg : Real;
begin
iTotal := 0;
for i := 1 to 5 do
iTotal := iTotal + arrMarks[i];
rAvg := iTotal / 5;
iHigh := arrMarks[1];
iPos := 1;
for i := 2 to 5 do
if arrMarks[i] > iHigh then
begin
iHigh := arrMarks[i];
iPos := i;
end;
memOutput.Lines.Add('Total: ' + IntToStr(iTotal));
memOutput.Lines.Add('Average: ' + FloatToStrF(rAvg, ffFixed, 8, 1));
memOutput.Lines.Add('Top learner: ' + arrNames[iPos] + ' (' + IntToStr(iHigh) + ')');
end;