ASP.NET Basics, Part 4: Looping the Loop

Last time, I introduced you to C#'s "if-else" family of conditional statements and explained how they could be used in combination with comparison and logical operators to control program flow and execution... This week, I'm going to proceed a little further down the road, with a look at the different types of loops supported by C# (and, by extension, ASP.NET).

Contributed by
Rating: 4 stars4 stars4 stars4 stars4 stars / 21
October 20, 2003
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement
Last time, I introduced you to C#'s "if-else" family of conditional statements and explained how they could be used in combination with comparison and logical operators to control program flow and execution. I also explained how conditional statements could be nested within one another, and wrapped things up with a discussion of the "switch" conditional statement.

This week, I'm going to proceed a little further down the road, with a look at the different types of loops supported by C# (and, by extension, ASP.NET). As always, I'll begin with a definition for those of you coming at this series from a non-programming background. In geek-talk, a "loop" is precisely what you would think - a programming construct that allows you to execute a set of statements over and over again, until a pre-defined condition is met.

C# offers a wide range of loops, in keeping with its profile as a next-generation programming language. It has the "while" and "do-while" loops, for situations involving a variable number of loop iterations, as well as the traditional "for" loop for loops involving a pre-defined number of iterations. Over the next few pages, I'll explain these loops in greater detail, together with examples and illustrations of how they can be used.

Every programming language worth its salt uses loops, and, incidentally, so do many shampoo manufacturers. Think lather-rinse-repeat, and you'll see what I mean.

Counting Down

The most basic loop available in C# is the "while" loop, and it looks like this:


while (condition)
{
        do 
this!
}



Or, to make the concept clearer,


while (rich Uncle Ed's still breathing)
{
        be nice to him
}



The "condition" here is a standard C# conditional expression, whichevaluates to either true or false. So, were you told to write the aboveexample in C#, it would look like this:


while (rich_old_guy_lives == 1)
{
        
be_nice();
}



The "while" control structure tests the conditional expression first,and only proceeds to execute the statements within the loop if theexpression evaluates to true.

How about an example to demonstrate the "while" loop?


<script language="C#" runat="server">
void Page_Load()
{  
        
// define a variable for the countdown
        
int countdown 10;
       
        
output.Text "Beginning countdown...";
       
        
// repeat the statement so long as the
        // variable is greater than or equal
        // to zero
        
while(countdown >= 0)
       {
                
output.Text += "
countdown;
                
countdown--;   
        }
       
        
output.Text += "<h1>Houston, we have lift-off!</h1>";
       
}      
</script>
<html>
<head><title>Countdown To Launch</title></head>
<body>
<asp:label id="output" runat="server" />
</body>
</html>



Here is the output.

Beginning Countdown...
10
9
8
7
6
5
4
3
2
1
0

Houston, we have lift-off!



Each loop requires a variable, or "loop counter," to track the number of iterations. In the example above, this variable is called "countdown." I have initialized it to 10, since the loop will start counting down from that value.

Next, we have the "while" loop proper:


<%
        while(
countdown >= 0)
       {
                
output.Text += "
countdown;
                
countdown--;   
        }
%>



This is pretty straightforward stuff. The "while" statement will checkif the value of the "countdown" variable is greater than or equal tozero. If it is, it will enter the loop and execute the enclosedstatements (in this case, print the value of the variable followed by aline break). It then decrements the value of the "countdown" variable byone (using the -- operator discussed previously), and repeats theprocedure.

On the eleventh iteration, the value of the countdown variable will be-1. Therefore, the result of the conditional statement will be false,the loop will be exited and the statements following the loop will beprocessed.

What if you forget to decrement the value of the loop counter (a commonnewbie mistake)? Start praying, and flip the page.

The Infinite Loop and the Careless Coder

A word of caution to novice programmers (and careless experienced onesalso): if you fail to provide a valid condition to exit your loop, youwill get stuck in an infinite loop, one of the worst nightmares for adeveloper.

The likely symptom of this condition in the ASP.NET context is a serverthat fails to respond for an extended period of time while executing thescript. In such a situation, you can rest assured that an infinite loopis the most likely culprit. Don't take my word for it, try it foryourself (note that the following code deliberately introduces aninfinite loop for illustrative purposes, so use it at your own risk):


<script language="C#" runat="server">
void Page_Load()
{  
       
        
// define a loop counter
        
int countdown10;
       
        
output.Text "Beginning countdown...";
       
        
// repeat
        
while(countdown >= 0)
       {
                
output.Text += "
countdown;
              
// don't change the loop counter, thereby introducing
              // an infinite loop
                // countdown--;
        
}
       
        
output.Text += "<h1>Houston, we have lift-off!</h1>";
       
}      
</script>
<html>
<head><title>Countdown To Launch</title></head>
<body>
<asp:label id="output" runat="server" />
</body>
</html>



This example deliberately "forgets" to alter the value of the loopcounter every time the loop runs. As a result, the conditional testalways ends up true and the script never exits the "while" loop. Hence,the Web server continues to execute the script (and eat memory) tillsuch time as you forcibly terminate the script by shutting down theserver, or the server times out.

Since Web servers can't rely on a human being around 24/7 to monitor theserver and kill rogue scripts, most of them include built-in safeguardsto ensure that such rogue scripts do not completely take over systemresources. They do this by including a timeout period, which specifiesthe maximum amount of time given to a particular script to completeexecution. If the script exceeds this time limit, the Web server willautomatically halt further execution of the script and return an error.For the IIS server, you can modify this value using the Internet ServiceManager; read more about this athttp://www.microsoft.com/windows2000/en/server/iis/htm/core/iipy_32.htm.

Note, however, that just because the Web server has this built-intimeout capability, it is not an excuse for you, the developer, to writesloppy code; until the server timeout is activated, other requests willbe queued unnecessarily, affecting the performance of the server andannoying your users. Therefore, it is important to always ensure thatyour loop has a valid exit condition...because prevention is better thancure!

Dos and Don'ts

A close cousin of the "while" loop is the "do-while" loop, whichgenerally looks like this:


do
{
        do 
this!
} while (
condition)

Wondering what the difference is between this one and the previous one?Try this next example in your browser:


<script language="C#" runat="server">
void Page_Load()
{  
        
int bingo 366;

        
// script will never enter the loop
        // since the condition is false
        
while (bingo == 699)
        {      
                
output.Text "Bingo!";
        }
}      
</script>
<html>
<head><title>Dos and Don'ts</title></head>
<body>
<asp:label id="output" runat="server" />
</body>
</html>



And here is the output:



What output?

The reason for the blank page is simple. If you take a closer look atthe code listing above, you will notice that the conditional statementevaluates to false at the first iteration itself. As a result, thescript never enters the "while" loop.

Now, there may be occasions when you need to execute a particular set ofstatements at least once before you check for a valid conditionalexpression. Consider the example of an interactive session with a storemanager adding items to the store inventory. You might want to force himto add at least one item. Once he has added a single item, you can askif he wishes to add more; if yes, allow him to continue, otherwiseterminate the session. A "do-while" loop fits this situation well: theconstruction of the "do-while" loop is such that the statements withinthe loop are executed first, and the condition to be tested is checkedafter.

The next example will demonstrate this:


<script language="C#" runat="server">
void Page_Load()
{  
       
        
int bingo 366;
       
        do
        {      
                
output.Text "Bingo!";
        } while (
bingo == 699);
}      
</script>
<html>
<head><title>Dos and Don'ts</title></head>
<body>
<asp:label id="output" runat="server" />
</body>
</html>



And here is the output:

Bingo!



In this case, the script will always execute the statements within theloop at least once. Subsequent iterations are subject to the evaluationof the conditional expression of the "do-while" loop. In the exampleabove, the expression evaluates to false, resulting in immediate exitfrom the loop after the first iteration. This is clearly seen in theoutput above.

How about another example to make things clearer? This next one rewritesthe countdown example using the "do-while" loop below:


<script language="C#" runat="server">
void Page_Load()
{  
       
        
// define a loop counter
        
int countdown10;
       
        
output.Text "Beginning countdown...";
       
        
// repeat so long as the variable
       // is greater than or equal to zero
        
do {
                
output.Text += "
countdown;
                
countdown--;   
        } while (
countdown >= 0);
       
        
output.Text += "<h1>Houston, we have lift-off!</h1>";
       
}      
</script>
<html>
<head><title>Countdown To Launch</title></head>
<body>
<asp:label id="output" runat="server" />
</body>
</html>



And here's the output:

Beginning countdown...
10
9
8
7
6
5
4
3
2
1
0


Houston, we have lift-off!



The bottom line: using a "do-while" loop ensures that the code withinthe loop will be executed at least once, regardless of whether or notthe conditional expression evaluates as true.

For-gone Conclusion

Both the "while" loop and its close cousin, the "do-while" loop, areused when you don't know for certain how many times the program shouldloop. But C# also comes with a mechanism for executing a set ofstatements a specific number of times - and it's called the "for" loop:


for (initial value of counterconditionupdate counter)
{
        do 
this!
}



Looks like gibberish? Well, hang on there a minute. The "counter" hereis a C# variable that is initialized to a numeric value, and keeps trackof the number of times the loop is executed. Before each execution ofthe loop, the "condition" is tested - if it evaluates to true, the loopwill execute once more and the counter will be appropriatelyincremented; if it evaluates to false, the loop will be broken and thelines following it will be executed instead.

Let's look at an example:


<script language="C#" runat="server">
void Page_Load()
{  
       
        
int number 7;

        
// use a for loop to calculate tables for that number
        
for (int x=1x<=15x++)
       {
                
output.Text += number " X " " = " + (number*x) +
"
"
;
        }
       
}      
</script>
<html>
<head><title>Turning The Tables, ASP.NET-Style!</title></head> <body>
<h3>Turning The Tables, ASP.NET-Style!</h3> <asp:label id="output"
runat="server" /> </body> </html> 



And here's the output:

Turning The Tables, ASP.NET-Style!

7 X 1 = 7
7 X 2 = 14
7 X 3 = 21
7 X 4 = 28
7 X 5 = 35
7 X 6 = 42
7 X 7 = 49
7 X 8 = 56
7 X 9 = 63
7 X 10 = 70
7 X 11 = 77
7 X 12 = 84
7 X 13 = 91
7 X 14 = 98
7 X 15 = 107


Let's dissect this a little bit.


<%
int number 7;
%>



Right up front, a variable is defined, containing the number to be usedfor the multiplication table. I've used 7 here - you might prefer to useanother number.


<%
// use a for loop to calculate tables for that number
for (int x=1x<=15x++)
{
        
output.Text += number " X " " = " + (number*x) + "
"
;
} %> 



Next, a "for" loop has been constructed, with "x" as the countervariable. If you take a look at the first line of the loop, you'll seethat "x" has been initialized to 1, and is set to run no more than 15times.

Finally, the script takes the specified number, multiplies it by thecurrent value of the counter, and displays the result on the page byvirtue of the "Text" attribute of the "output" label server control.

The Sound of Breaking Loops

When dealing with loops, there are two important keywords you should beaware of: "break" and "continue". You might remember that I dealt withthese briefly in the previous section of this tutorial; let's now take acloser look, since these keywords come in handy when dealing with loopsas well.

First, the "break" keyword. This is usually used to exit a loop when itencounters an unexpected situation. A good example of such a situationis the dreaded "division by zero" error: when dividing one number byanother one (which keeps decreasing), it is always advisable to checkthe divisor on every iteration and take action (either exit the loop orskip to the next iteration) once it becomes equal to zero.

Take a look:


<script language="C#" runat="server">
void Page_Load()
{
        
// some variables to play with 
        
int dividend 7;
        
int divisor 10;
       
        
// a for loop to perform division
        
for(int count 1count <= 15count++)
       {
       
                
// if divisor is zero
                // get out now
                
if(divisor == 0)
                {
                        break;
                }
               
              
// print loop counter and perform division
                
output.Text += "Loop counter is " count "." " ";
                
output.Text += dividend " / " divisor " = " +
((double)
dividend/divisor) + "
"
;
              
// decrement divisor
                
divisor--;
        }
       
        
output.Text += "<h3>Divisor is zero, time to stop!</h3>";
}      
</script>
<html>
<head></head>
<body>
<h3>Divide And Conquer</h3>
<asp:label id="output" runat="server" />
</body>
</html>



Here's the output:

Divide And Conquer

Loop counter is 1. 7/10 = 0.7
Loop counter is 2. 7/9 = 0.777777777777778
Loop counter is 3. 7/8 = 0.875
Loop counter is 4. 7/7 = 1
Loop counter is 5. 7/6 = 1.166666666666667
Loop counter is 6. 7/5 = 1.4
Loop counter is 7. 7/4 = 1.75
Loop counter is 8. 7/3 = 2.333333333333333
Loop counter is 9. 7/2 = 3.5
Loop counter is 10. 7/1 = 7

Divisor is zero, time to stop!



In this example, I have defined two variables, a dividend and a divisor.Next, I've used a "for" loop to divide the two values by each other afixed number of times (15). Note that I have also decremented the valueof the "divisor" variable by one for every iteration of the loop.

Obviously, at some point of time, "divisor" will become zero. Anyattempt to continue division after this point will result in ugly C#error messages about illegal operations. This is where the "break"statement comes in - it can be used to exit the "for" loop as soon asthe value of the variable "divisor" becomes zero.

Should I pat myself on my back? Not really.

Take another look at the output and compare it against the code listing.You will see that the code exited the "for" loop before the conditionfor the loop became false.

Ideally, the script should exit the "for" loop when the value of the"count" variable becomes greater than 15, and, until then, shouldperform division for all values of the divisor other than 0 (includingnegative values).

In the example above, the "break" statement caused it to exit once thedivisor becomes 0 (on the tenth iteration of the loop). Therefore, onlypositive divisor values are taken care of by the code above; divisionoperations involving negative values of the divisor never even see thelight of day.

Is there a way to fix this? Sure, with the "continue" keyword. Take alook:


<script language="C#" runat="server">
void Page_Load()
{
        
// some variables to play with 
        
int dividend 7;
        
int divisor 10;
       
        
// a for loop to perform division
        
for(int count 1count <= 15count++)
       {
       
                
// if divisor is zero
                // decrement divisor and continue
                
if(divisor == 0)
                {
                        
divisor--;
                        continue;
                }

              
// print loop counter and perform division
                
output.Text += "Loop counter is " count "." " ";
                
output.Text += dividend " / " divisor " = " +
((double)
dividend/divisor) + "
"
;
                
divisor--;
        }
       
        
output.Text += "<h3>All done, time to stop!</h3>";
}      
</script>
<html>
<head></head>
<body>
<h3>Divide And Conquer</h3>
<asp:label id="output" runat="server" />
</body>
</html>



Here's the output:

Divide And Conquer

Loop counter is 1. 7/10 = 0.7
Loop counter is 2. 7/9 = 0.777777777777778
Loop counter is 3. 7/8 = 0.875
Loop counter is 4. 7/7 = 1
Loop counter is 5. 7/6 = 1.166666666666667
Loop counter is 6. 7/5 = 1.4
Loop counter is 7. 7/4 = 1.75
Loop counter is 8. 7/3 = 2.333333333333333
Loop counter is 9. 7/2 = 3.5
Loop counter is 10. 7/1 = 7
Loop counter is 12. 7/-1 = -7
Loop counter is 13. 7/-2 = -3.5
Loop counter is 14. 7/-3 = -2.3333333333333333
Loop counter is 15. 7/-1 = -1.75

All done, time to stop!



In this revised example, when the value of the "divisor" variablebecomes zero, I decrement its value and call the "continue" keyword.This "continue" keyword skips over the current iteration of the loop andsend control of the program back to the start of the "for" loop for thenext iteration (unlike the "break" statement, which simply exits theloop immediately). As a result, the script continues to iterate throughthe "for" loop until the conditional statement is no longer true, andthe value of the "count" variable becomes greater than 15.

For obvious reasons, there is no output for that particular iteration ofthe loop when the value of "divisor" variable is zero.

End of Play

That's about it for this article. Over the last few pages, I listedthe different types of loops available to C# programmers, and showed youhow they can be used. I started with the "while" loop, used to repeat aset of statements until a given condition becomes false. Its closecousin, the "do-while" loop, is used to ensure that a "while" loopexecutes at least once, regardless of the state of the conditionalexpression.

For situations which don't involve as much uncertainly about the totalnumber of loop iterations, there's the "for" loop, useful when you knowthe exact number of iterations the loop should run for. Finally, Idemonstrated the "break" and "continue" keywords, which come in handy toexit a loop and skip over particular iterations of the loop,respectively.

That's about all the time we have for this week. Next week, I shallintroduce you the wonderful world of complex variables - arrays,enumerations and structures - that build on the simple variables you'veencountered thus far to allow more complex storage and manipulation of
blog comments powered by Disqus
ASP.NET ARTICLES

- Implementing ASP.NET 4.0 Page.MetaDescriptio...
- ASP.Net Development Tips
- Intro to Sessions in ASP.Net
- Google Maps API Introduction in ASP.NET usin...
- Creating an ASP.NET 3.5 Gridview Image Galle...
- Encrypt QueryString in ASP.NET 3.5 using VB....
- ASP.NET 3.5 Drop Down List Controls
- Connect to Access Database with ASP.Net
- Secure Audio Streaming with ASP.Net and Flash
- Dynamic Sitemap and Navigation in ASP.Net
- Implement Gzip and Deflate Compression in AS...
- Run ASP.Net in Ubuntu with Apache
- ASP.Net Mono Website Contact Forms
- ASP.Net URL Rewriting Methods
- Murach`s ASP.NET 4 Web Programming with C# 2...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 11 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials