Loops in C#

In many cases either for, while or do can perform the same task.
Each of the programs below put the numbers from 1 to 10 in a list box. he Do Loop is similar to the While loop except that it does the test at the end of the loop. A do loop executes one or more times because the test is at the end.
For loops and While loops execute zero or more times because the test is at the beginning.


The for loop initializes the variable, compares to end point, and increments:

for(int num=1; num<=10;num++)
{
  listBox1.Items.Add(num);
}

The while loop only does the comparison. We initialize the variable before the loop and increments it as the last thing in the loop.

  int num = 1;
  while(num<=10)
  {
    listBox1.Items.Add(num);
    num++;
  }
 

The do loop also only does the comparison. We initialize the variable before the loop and increments it as the last thing in the loop.
It is important to note that a do loop ALWAYS executes at least once. The for and while loops can execute 0 times because the test is done before the loop starts.

int num = 1;
do
{
  listBox1.Items.Add(num);
  num++;
} while (num <= 10);

NEXT: Nested Loops