Grade 10 · Loops & first strings · Lesson and coding task · about 14 minutes
Open this task in the Delphi workspace →
The running total is the single most useful loop pattern you will ever learn. Start a total at 0 before the loop, then add to it inside the loop:
rTotal := 0; // initialise BEFORE the loop
for i := 1 to iMonths do
begin
rTotal := rTotal + rMonthly; // accumulate
memOutput.Lines.Add('Month ' + IntToStr(i) + ': R ' +
FloatToStrF(rTotal, ffFixed, 10, 2));
end;
rTotal := rTotal + rMonthly reads strangely at first — "the new total becomes the old total plus this month's money". That one line powers every sum, average and counter you will write.
Your task: stokvel savings
A stokvel member saves a fixed amount every month. Show the balance month by month, and the final amount on the label.
What you will do
- Read the monthly amount (Real) and the number of months (Integer)
- Loop through the months, adding to a running total
- Each memo line: Month 3: R 750.00
- lblTotal shows: Saved: R 1000.00
Hints
- rTotal := 0; must happen before the loop starts.
- Inside the loop: rTotal := rTotal + rMonthly; then add the memo line.
- The loop body has two statements, so it needs begin … end.
Model solution
procedure TfrmStokvel.btnCalcClick(Sender: TObject);
var
rMonthly, rTotal : Real;
i, iMonths : Integer;
begin
rMonthly := StrToFloat(edtMonthly.Text);
iMonths := StrToInt(edtMonths.Text);
rTotal := 0;
for i := 1 to iMonths do
begin
rTotal := rTotal + rMonthly;
memOutput.Lines.Add('Month ' + IntToStr(i) + ': R ' + FloatToStrF(rTotal, ffFixed, 10, 2));
end;
lblTotal.Caption := 'Saved: R ' + FloatToStrF(rTotal, ffFixed, 10, 2);
end;