Tutorials
Desktop Programming
C Sharp
WHILE LOOPS IN C#
Written by Christopher Thursday, 29 May 2008 16:04
Tutorials
INTRODUCTION
C# provides several mechanisms for flow control in a program. The loops in C# allow you to execute a block of code repeatedly, until a certain condition is met. This condition can be the number of repetition, a variable taking a specified value or something completely different. The while loop is a pre-test loop and is used to execute a block of code for a number of times not known before the loop begins. The do..while loop is a post-test loop and is used for the same purposes as the while loop.
SYNTAX AND USE: WHILE LOOP
The syntax for a while loop is the following one:
While(condition)
Statement;
Usually, the while loop will check a Boolean variable and act according to its value. If the condition is true, the loop will execute again. If at a point the condition results to false the loop will not be executed. Take notice that if the value of the control variable changes to false inside the loop variable and then to true before the end of the loop, nothing will happen. The condition is evaluated just before an iteration is to begin, not during the execution of the loop statements. The following example illustrates a basic while loop:
static void Main(string[] args)
{
bool condition = true;
while (condition)
{
//Execute som statements
// assign new condition value:
condition = checkCondition();
}
}
It is important that the condition value changes inside the loop. If the condition value can’t change inside the loop, it will never stop executing.
SYNTAX AND USE: DO…WHILE LOOP
This loop is the post-test version of the while loop. The difference of the do…while loop from the while loop is that the first will execute at least one time. This is due to the fact that the condition statement is evaluated after the first execution of the loop. The following snippet of code demonstrates the basic usage of the do…while loop:
static void Main(string[] args)
{
bool condition = true;
do
{
AfunctionToBeCalledAtLeastOnce();
condition = CheckCondition();
}
while (condition);
}
In the previous example we have a function that must be called at least once. When the program reaches the do…while loop it enters the loop and an iteration takes place. The condition statement is assigned a value. After the successful completion of the loop the condition statement is evaluated. If it is true a new iteration will take place. If not, the program will continue normally.

| < Prev | Next > |
|---|
| Training Tip #1 :: Push-ups on the Swiss Ball admin 28.4.2009 7:07 |
Re:hello admin 21.4.2008 14:11 |
| Dell Inspiron 1545 Windows XP Drivers admin 12.4.2009 8:03 |
hello yuppy 21.4.2008 10:28 |
| Re:Get rich ebooks - are they really working? lann 23.4.2008 17:04 |
Re:Get rich ebooks - are they really working? admin 19.4.2008 14:08 |