LearnStanmorephysics

Grade 11 · Powering Up

WHILE loops

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

Hints
  1. Set rSaved := 0; and iMonths := 0; before the loop.
  2. The condition is rSaved < rGoal — the loop stops as soon as the goal is reached or passed.
  3. 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;

About this material

This platform provides original CAPS-aligned practice material and study tools. Content is machine-verified and has not been reviewed by subject specialists. It is not affiliated with or endorsed by the Department of Basic Education. Learners should also use official past papers and consult their teachers where uncertain.