Search results for 'While Loop'. 1 post(s) found.

  1. 2009/09/05 How to implement while loop in C# ?
2009/09/05 09:21

How to implement while loop in C# ?


A While Loop will check a condition and then continues to execute a block of code as long as the condition evaluates to a boolean value of true. Its syntax is as follows: while (<boolean expression>) { <statements> }.  The statements can be any valid C# statements. The boolean expression is evaluated before any code in the following block has executed. When the boolean expression evaluates to true, the statements will execute. Once the statements have executed, control returns to the beginning of the While Loop to check the boolean expression again.

When the boolean expression evaluates to false, the While Loop statements are skipped and execution begins after the closing brace of that block of code. Before entering the loop, ensure that variables evaluated in the loop condition are set to an initial state. During execution, make sure you update variables associated with the boolean expression so that the loop will end when you want it to. Listing 4-1 shows how to implement a While Loop.

Following is the example.

int myInt = 0;

while (myInt < 10)
{
  Console.Write("{0} ", myInt);
  myInt++;
}
Console.WriteLine();
Trackback 0 Comment 0

Trackback : Cannot send a trackbact to this post.