Skip to main content
CSharpUniversity ASP.NET and C# lessons

The search runs entirely in your browser over the published lesson list.

Lab: repeating work with the for loop

The for loop repeats a block a known number of times. Its three parts look cryptic until you name them.

The three parts

  1. Where to start.
  2. How long to keep going.
  3. How to move forward each time.
C#
for (int i = 1; i <= 5; i++)
{
    outputLabel.Text += "Row " + i + "<br>";
}

The task

Print a small times table. Then change the start and end values and predict the output before you run it.

Off by one. Decide whether the last number should be included, then choose less than or less than or equal accordingly. Most loop bugs are a wrong boundary, not a wrong idea.

When you do not know the number of repeats in advance, the while loop lab is the better tool.

New lessons by email

Leave your address and get a short note whenever a fresh lesson is published. No account needed and you can stop at any time.

Thank you. Your address has been noted in this browser session. Connect a mailing service to deliver the notes for real.