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
- Read the number of rows from edtRows
- Outer loop for rows; inner loop builds each row of stars
- Row 3 is exactly ***
Hints
- Reset sLine := ''; at the start of every outer lap, or the stars snowball.
- The inner loop runs for iCol := 1 to iRow — that is what makes each row one star longer.
- 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;