Zebra0.com

csharp loops

The while loop uses a Boolean expression to determine when to end the loop:
The format of a while loop is:

while <Boolean expression>
{ <statements>

}

The examples below compares a for and a while Loop. Both examples generate the values 1, 2, 3, 4, 5.

 

For Loop:

 

While Loop:

 

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

 

int n = 0; //initialize the variable
while (n <10)
{
listBox1.Items.Add(n);
n++; //increment the variable
}

(One advantage of the while loop is that the Boolean expression can include AND and OR.)

Modify the program to generate powers of 2 using the code shown below:

//Programmer: Janet Joy
//While loop generates 1,2,4,8,...512
private void Form1_Load(object sender, EventArgs e)
{
   listBox1.Sorted = false;
   int n = 1; //initialize the variable
   while (n < 1000)
   {
      listBox1.Items.Add(n);
      n = n * 2; //increment the variable
   }
}

End of lesson, Next lesson: