Tuesday, March 30, 2010

The while Loop

The C# for loop described in C# Looping - The for Statement previously works well when you know in advance how many times a particular task needs to be repeated in a program. There will, however, be instances where code needs to be repeated until a certain condition is met, with no way of knowing in advance how many repetitions are going to be needed to meet that criteria. To address this need, C# provides the while loop (yet another construct inherited by C# from the C Programming Language).


The C# while Loop :

Essentially, the while loop repeats a set of tasks until a specified condition is met. The while loop syntax is defined follows:

while (''condition'')
{
// C# statements go here
}

where condition is an expression that will return either true or false and the // C# statements go here comment represents the C# code to be executed while the condition expression is true. For example:

int myCount = 0;

while ( myCount <>
{
myCount++;
}

In the above example, the while expression will evaluate whether the myCount variable is less than 100. If it is already greater than 100 the code in the braces is skipped and the loop exits without performing any tasks.

If, on the other hand, myCount is not greater than 100 the code in the braces is executed and the loop returns to the while statement and repeats the evaluation of myCount. This process repeats until the value of myCount is greater than 100, at which point the loop exits.


No comments:

Post a Comment