Grade 11 · Conditional loops · Lesson and coding task · about 12 minutes
Open this task in the Delphi workspace →
A FOR loop needs to know in advance how many times to run. A WHILE loop runs for as long as a condition stays True — perfect for "keep going until…" problems:
while rSaved < rGoal do
begin
rSaved := rSaved + rMonthly;
Inc(iMonths); // same as iMonths := iMonths + 1
end;
Three things keep a WHILE loop healthy:
- Initialise the variables in the condition before the loop.
- The condition is tested before every lap — if it is False at the start, the body never runs.
- Something inside the loop must move the condition towards False, or you have an endless loop. (Try it here — we will catch it and tell you off gently.)
Your task: months to reach a savings goal
Given a goal amount and a monthly deposit, work out how many months it takes to reach (or pass) the goal — showing the balance month by month.
What you will do
- Read the goal and monthly amount
- WHILE the saved amount is below the goal: add a month's money, count the month, show the balance line Month 2: R 500.00
- lblMonths shows: Reached in 4 months
Hints
- Set rSaved := 0; and iMonths := 0; before the loop.
- The condition is rSaved < rGoal — the loop stops as soon as the goal is reached or passed.
- Inc(iMonths) adds 1 to the month counter.
Model solution
procedure TfrmGoal.btnPlanClick(Sender: TObject);
var
rGoal, rMonthly, rSaved : Real;
iMonths : Integer;
begin
rGoal := StrToFloat(edtGoal.Text);
rMonthly := StrToFloat(edtMonthly.Text);
rSaved := 0;
iMonths := 0;
while rSaved < rGoal do
begin
rSaved := rSaved + rMonthly;
Inc(iMonths);
memOutput.Lines.Add('Month ' + IntToStr(iMonths) + ': R ' + FloatToStrF(rSaved, ffFixed, 10, 2));
end;
lblMonths.Caption := 'Reached in ' + IntToStr(iMonths) + ' months';
end;