Using while and do...while to Loop an Indeterminate Number of Times


Using while and do...while to Loop an Indeterminate Number of Times

In some situations, you won't know the exact number of times a loop must be performednot even when the loop begins. You could start a for loop specifying an upper limit that you know is larger than the number of loops needed, check for a terminating condition within the loop, and exit the loop using a break statement when the condition is met. However, this approach is inefficient and usually impractical. When you need to create such a loop, using do...while is the answer.

Creating a do...while

The most basic form of a do...while has the following syntax:

do statement while (expression);


By the Way

The following syntax is used to execute multiple statements:

do {    [Statements] } while (expression);



Ending a do...while Loop

A do...while loop without some sort of exit mechanism or defined condition is an endless loop. In its most basic form, nothing is present to tell the loop when to stop looping. At times you may need an endless loop (game programming is an example), but more often, you'll need to exit the loop when a certain condition is met. As with the for loop, you can use the break statement to exit a do...while loop at any time. For example, you could expand the do...while loop to include a break statement like the following:

do {    Statements    if (expression)       break; } while (x==x);


In this code, the loop would execute until expression evaluates to true. Generally, the expression is based on a variable that's modified somewhere within the loop. Obviously, if the expression never changes, the loop never ends.

Another flavor of the while loop is the while...do loop. The following is a simple while...do loop:

while (expression) statement


or

while (expression) {    Statements }


As long as expression evaluates to true, the loop continues to occur. If expression evaluates to false when the loop first starts, the code between the statement(s) doesn't executenot even once.

The difference between the do...while and the while loops is that the code statements within the do...while loop always execute at least once; expression isn't evaluated until the loop has completed its first cycle. Therefore, such a loop always executes at least once, regardless of the value of expression. The while loop evaluates the expression first; therefore, the statements associated with it may not execute at all.

Creating a do...while Example

You're now going to create an example using a do...while. In this project, you are going to find the first 10 numbers that are evenly divisible by 3. Although you know you want to find 10 numbers, you don't know how many numbers you will have to evaluatetherefore the do...while is the best choice.

Create a new Windows application named No Remainders and then follow these steps:

1.

Right-click Form1.cs in the Solution Explorer, choose Rename, and then change the name of the default form to frmNoRemainders.cs. Next, set the Text property of the form to No Remainders.

2.

Add a button to the form and set the new button's properties as follows:

Property

Value

Name

btnFindNumbers

Location

99,39

Size

94,23

Text

Find Numbers


3.

Add a ListBox control to the form and set its properties as follows:

Property

Value

Name

lstResults

Location

86,86

Size

120,160


Your form should now look like the one shown in Figure 14.3.

Figure 14.3. What better control to show a list of results than a list box?


Double-click the new button to access its Click() event and then enter the following code:

int intSeek = 1; int intFound = 0; do {    if ((intSeek % 3) == 0)    {       lstResults.Items.Add(intSeek.ToString());       intFound++;    }    intSeek++; } while (intFound < 10);


Again, this code is more easily understood when broken down:

  • The first two statements simply create a couple of integer variables. The variable intSeek will be the number we'll test to see whether it's evenly divisible by three (meaning it has no remainder). The variable intFound will be our counter; we'll increment this by one each time we find a number evenly divisible by three.

  • The do statement starts the loop. There is no condition at the start of the loop because we want the loop to execute at least once we test the condition at the end of the loop using while.

  • In Hour 12, "Performing Arithmetic, String Manipulation, and Date/Time Adjustments," I mentioned how the % operator can be used to determine a remainder. Here we're using % to determine if intSeek is evenly divisible by three by seeing if there is a remainder when intSeek is divided by 3.

  • If the number in question is evenly divisible by 3 (there is no remainder), the number in intSeek is added to the results list box and intFound is incremented by 1.

  • The next statement is the closing curly brace for the if construct. After this, intSeek is incremented by 1. Notice that intSeek is incremented during each pass of the loop, since the statement is placed outside of the if block.

  • The last statement closes the loop. It also tests intFound and, and if less than 10 numbers have been found, the loop code gets executed again.

Click Save All on the toolbar to save the project and then press F5 to run it. Click the Find Numbers button and watch the results fill upfast (see Figure 14.4)!

Figure 14.4. Visual C# performs math functions very fast.


The do...while loop was the best choice here because we really didn't know how many numbers we were going to have to evaluate (that is, how many times to iterate the loop). If we only wanted to search the numbers from 1 to 100, for example, a for loop would have been better.




Sams Teach Yourself Microsoft Visual C# 2005 in 24 Hours, Complete Starter Kit
Sams Teach Yourself Visual C# 2005 in 24 Hours, Complete Starter Kit
ISBN: 0672327406
EAN: 2147483647
Year: N/A
Pages: 248
Authors: James Foxall

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net