Nesting


As we just covered making decisions and performing repetitive actions using loops, there are often cases where you will want to use one of these constructs inside another. This kind of coding technique is called nesting and is very useful. Let's take a look at an example of how it works right now.

Try It Out—Nested Loops

Here is an example using our snake eyes game. Make a copy of the DoUntil.aspx page and rename it Nesting.aspx. Modify the code in Nesting.aspx by adding a nested Do loop
as follows:

Sub Button1_Click(sender As Object, e As EventArgs)   Label1.Text = ""  Dim dice1, dice2, score, counter As Integer  For counter = 1 to 10  score = 0  Do  dice1 = Int(Rnd() * 6) + 1  dice2 = Int(Rnd() * 6) + 1  score = score + (dice1 + dice2)  Label1.Text = Label1.Text & "Rolled a " & dice1 & " and a " & _  dice2 & "<br/>"  Loop Until dice1 = 1 And dice2 = 1  score = score - 2  Label1.Text = "Game " & counter.ToString() & _  ": Total score would have been " & score & "<br/><br/>" & Label1.Text  Next counter End Sub

When you run the page and press the button, the code will play the Snake Eyes game for you, not once, not twice, not three times, but ten times, as that is the value we have specified in the For clause with the counter variable. You should see something like the following:

click to expand

How It Works

Each iteration of the For loop runs the complete Do loop within it once. Since the Do loop runs the Snake Eyes game and the For loop iterates 10 times (from 1 to 10), this example runs the Snake Eyes game 10 times.

We'll be covering functions and procedures next in this chapter, and at the end of that section, we will come back to nesting and see a quick reference on how it can be applied to these kinds of code blocks.




Beginning Dynamic Websites with ASP. NET Web Matrix
Beginning Dynamic Websites: with ASP.NET Web Matrix (Programmer to Programmer)
ISBN: 0764543741
EAN: 2147483647
Year: 2003
Pages: 141

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