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
- Where to start.
- How long to keep going.
- 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.