C Sharp Looping with do and while Statements

From Techotopia
Revision as of 19:13, 17 January 2008 by Neil (Talk | contribs) (New page: 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 need...)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

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 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 < 100 )
{
      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.

C# do ... while loops

It is often helpful to think of the do ... while loop as an inverted while loop. The while loop evaluates an expression before executing the code contained in the body of the loop. If the expression evaluates to false on the first check then the code is not executed. The do .. while loop, on the other hand, is provided for situations where you know that the code contained in the body of the loop will always need to be executed at least once. For example, you may want to keep stepping through the items in an array until a specific item is found. You know that you have to at least check the first item in the array to have any hope of finding the entry you need. The syntax for the do ... while loop is as follows:

do
{
       // C# statements here
} while (''conditional expression'')

In the do ... while example below the loop will continue until the value of a variable named i equals 0:

int i = 10;
do
{
       i--;
} while (i > 0)