Home Page
"Join my free Amazing ASP.NET newsletter"
It's safe and easy to signup. You get:
  • Notified anytime a new article comes out
  • Technical step-by-step tutorials on all important ASP.NET topics
  • Expert guidance so you can reach unlimited ASP.NET success
  • Important ASP.NET news updates
Enter your Email

Click here to download the sample source code for this while loop lab exercise 

In contrast to the for loop, the “while” loop is generally useful when you are not sure how many loop iterations you will execute a block of repetitive code.  The while loop keeps executing until the termination condition statement becomes false.  Let’s see an example.

Create another Button and TextBox in your Default3.aspx web form.  Change the Button to say “while loop” and creat the event handler.  Put the following code for the Button event handler:


int i = 1;
while (i <= 5)
    TextBox2.Text += i.ToString();

Notice the format of the while statement.  It is simpler than the for loop in that it only has a termination condition.  Basically this loop will keep executing as long as i is less than or equal to the value 5.  With the while loop (in contrast to the for loop), there must be something that happens inside the loop body (inside curly braces) that ensures that the loop will eventually terminate.  In our case, this is done by incrementing the i variable i++;  You must be careful not to create an infinite loop by forgetting to create some code inside the loop that ensures it will eventually terminate. 

Here is another way to write the while loop above using some extra C# code.  This will help you look at how we can use different techniques to accomplish the same thing:


int i = 1;
bool keeplooping = true;
while (keeplooping)
    TextBox3.Text += i.ToString();
    if (i > 5)
       keeplooping = false;

Above I used a boolean data type as the loop variable.  This technique is easier to read and maintain for some programmers and is a matter of style.  It also gives you more options to test for different termination conditions inside the loop.  Whenever you need to terminate the loop, you simply set the keeplooping variable to false.

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment