Loops in C#

A for loop is extremely powerful. A for loop has three parts. The parts are separated by semicolons. The format is shown below:

for (_______; _________; __________) ____________;
      first     test     at end       statement  

The first part assigns any initial values;
The second part is a Boolean expression. If this expression is true, the loop will continue;
The third part is anything you want to do at the end of the loop.

A for loop is a good choice when we know how many times we want the code to repeat.

If you work through the code carefully, you will notice that the value of i is 0, 1, and 2 inside the loop. When n becomes 3, the loop ends. When the loop ends, the next
statement after the loop is executed.

Another very important point to note is that the body of the loop is either the single
statement that follows the for clause, or all of the statements enclosed in curly braces{ }.

The program on the previous page could have been written as shown below. Notice that the variable can be delard e the loop. However, many programmers believe that it is better to always use the curly braces.

private void Form1_Load(object sender, EventArgs e)
{
  listBox1.Sorted = false;
  for(int num=0;num<6;num++)  listBox1.Items.Add(num);
}

Use the example and modify the code to create the output shown in each illustration. Try it before you look at the solutions.

6, 7, 8
solution

10, 9, 8, 7, 6, 5, 4, 3, 2, 1, Blast off
solution

NEXT: Microsoft Reference: while loops