Notice that the test value of 1000 is never hit exactly. If we had said while(n!=1000) it would be an endless or infinite loop!
When the while loop is executed, the Boolean expression is tested: if it is true the body of the loop is executed.
When it gets to the end of the loop (thee closing curly brace) it goes back to the top and tests again.
The loop is repeated until the test fails, then the next statement after the end of the loop is executed. A While loop can execute zero or more times.
After the value 512 is added to the list box, n is assigned a new value of 1024.
When the control goes to the while statement, the expression n<1000 is false and the loop ends.
When the loop ends the next statement after the loop is executed.
Note: If the Boolean expression is true, all of the statements in the loop execute, even if the expression becomes false during the loop.
Look at the difference in the output when the position of the increment is changed:
Everything is exactly the same except for the increment:
//Programmer: Janet Joy
//While loop generates 2,4,8,...1024
private void Form1_Load(object sender, EventArgs e)
{
listBox1.Sorted = false;
int n = 1; //initialize the variable
while (n < 1000)
{
n = n * 2; //increment the variable
listBox1.Items.Add(n);
}
}
End of lesson, Next lesson: