LearnStanmorephysics

Grade 11 · Powering Up

Nested loops

Grade 11 · Conditional loops · Lesson and coding task · about 12 minutes

Open this task in the Delphi workspace →

Put a loop inside a loop and you can work in two dimensions: rows and columns, weeks and days, learners and subjects. For every single lap of the outer loop, the inner loop runs completely:

for iRow := 1 to 4 do
begin
  sLine := '';
  for iCol := 1 to iRow do    // note: up to iRow!
    sLine := sLine + '*';
  memOutput.Lines.Add(sLine);
end;

That prints the classic staircase. The trick to read it: the inner loop builds one line, the outer loop adds the finished lines. Building a string with sLine := sLine + … is the string version of a running total.

Your task

Let the user choose the number of rows and draw the staircase:

*
**
***
****

What you will do

Hints
  1. Reset sLine := ''; at the start of every outer lap, or the stars snowball.
  2. The inner loop runs for iCol := 1 to iRow — that is what makes each row one star longer.
  3. Add the finished sLine to the memo after the inner loop ends (but still inside the outer loop).
Model solution
procedure TfrmPattern.btnDrawClick(Sender: TObject);
var
  iRow, iCol, iRows : Integer;
  sLine : String;
begin
  iRows := StrToInt(edtRows.Text);
  for iRow := 1 to iRows do
  begin
    sLine := '';
    for iCol := 1 to iRow do
      sLine := sLine + '*';
    memOutput.Lines.Add(sLine);
  end;
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.