ASP.NET Basics, Part 4: Looping the Loop - For-gone Conclusion
(Page 5 of 7 )
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 counter; condition; update 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=1; x<=15; x++)
{
output.Text += number + " X " + 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=1; x<=15; x++)
{
output.Text += number + " X " + 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.
Next: The Sound of Breaking Loops >>
More ASP.NET Articles
More By Harish Kamath (c) Melonfire