Control Structure

   

Control structure like all the other words and phrases that you've encountered so far that have made you think, "What the heck is that?" is just as simple to understand when explained in plain English.

When creating dynamic web applications, there are two types of code you program: code that always executes and code that conditionally executes. Control structure deals with the latter. It deals with controlling the flow of code that executes based on conditions.

At its heart, control structure is checking to see whether something is true or false and running code based on the answer.

In real life, we do this type of thing all the time as we go about our day. We may have never have identified the processes or even considered that our brains use what in programming is called control structure, but we do.

Think back to the last time you had lunch at a restaurant. You were presented with a menu, and you read down it looking for an item that tickled your fancy. Something that would fulfill your desire for some good eatin'. Maybe the menu looked like this:

  1. Garden Salad w/Soup

  2. Grilled Chicken Sandwich

  3. Bacon Double Cheeseburger

  4. Turkey Sandwich Wrap

Note

I must make a disclaimer that although most of the examples in this book to this point have been about food, I am not preoccupied with food.

(Note from Publisher: Peter is lying about his love for food. We're betting he will pick the Bacon Double Cheeseburger. Let's watch!)


Now you are faced with a few choices here. As you proceed down the menu, you will find yourself asking some questions. To simplify this example, I'll use just one question: "Do I want it?" Pretty simple. Let's go through the menu.

  1. Garden Salad

    • Do I want it? Nah!

  2. Grilled Chicken Sandwich

    • Do I want it? Nah!

  3. Bacon Double Cheeseburger

    • Do I want it? YES!

  4. Turkey Sandwich Wrap

    • No need to look at this; I've made my decision

(Note from Publisher: We told you he'd pick the cheeseburger.)

With this process, I am basically going through the list of items in the menu and asking the same question for each item. The following isn't a working code example but a plain English model of a thought process that will give you an example of a looping and branching process.

 1.Garden Salad  2.Grilled Chicken Salad  3.Bacon Double Cheeseburger  4.Turkey Sandwich Wrap  menuitem = "Garden Salad"  do this until I have said "yes!" to something on the menu      if I want (menuitem)then          Say "Yes!"      Otherwise          Say "Nah!"      And move on  Go to the next menu item and do it again 

This is a crude example of the process, but you can see both a loop statement as I go through the menu items and a branching statement as I decide whether I want the particular item I happen to be considering.

So the first time through the loop the question was "Do I want a garden salad?" Because I didn't, I said "Nah!" and moved on, went to the next menu item, and started over. I went through this process until I got to the cheeseburger, where my answer was "Yes!" When I went to the next item, there was no reason to proceed because I found something on the menu I liked.

As you can see, all day long we're branching and looping and looping and branching in our decision-making processes. Let's begin to take a look into each of these processes in more depth. You will see that dynamic programming as a whole and ASP.NET specifically depends heavily on different types of control structures.

Branching

To solidify what branching is, it's a test that helps us to control what blocks of code are executed based on the results of the text. There are two basic kinds of branching statements:

  • If > Then > Else. This provides a way to select a block of code to execute based on whether a specific condition is met. This is generally used when there are two or maybe a few possible conditions that need to be evaluated, but it is generally not used when there are many possibilities.

  • Select/Switch. This type of branch has a different name in each language, but they all perform the same action. In Visual Basic .NET, it is called a Select Case statement; and in C#, it is called a switch. This statement is used when there are many possible conditions that need to be checked.

If > Then > Else

When you are trying to assess the condition of something and execute a certain block of code based on that condition, the if statement in all its forms provides a powerful and versatile way to go about it. Look at the simple form of the if statement:

Visual Basic .NET
if Test then      Code that gets executed if test returns true  end if 
C#
if (test){     Code that gets executed if test returns true  } 

The way it works is pretty simple. If the test returns true, everything between the opening delimiter and closing delimiter executes. If it returns false, it ignores this code. Take a look at a working example now:

Visual Basic .NET branch_if_simple_vb.aspx
dim i as Integer  i=10  if i = 10 then      OurLabel.Text = "It matched"  end if 
C# branch_if_simple_cs.aspx
int i;  i = 10;  if (i == 10){      OurLabel.Text = "It matched";  } 

This block of code would return true, and "It matched" would be written to the page. Now let's go a step farther and give the statement an option if the test fails to match.

Visual Basic .NET branch_if_else_vb.aspx
dim i as Integer  i=10  if i = 11 then      OurLabel.Text = "It matched"  else      OurLabel.Text = "It didn't match"  end if 
C# branch_if_else_cs.aspx
int i;  i = 11;  if (i == 10){      OurLabel.Text = "It matched";  }else{      OurLabel.Text = "It didn't match";  } 

Because the value of the i variable is now 11, the test returns a value of false and the if > else statement now hits the else portion. This is where the word branching comes from. These different sections of code are known as code branches and, depending on the condition of the test results, determine which branch is run, just like the menu item that returned a positive response from my stomach/brain to determine what I would have for lunch.

If statements can be more complex as well. They can contain multiple branches using the elseif statement in Visual Basic .NET and else if statement in C#.

Warning

Be mindful that in Visual Basic .NET elseif is a single word and in C# it is two separate words else if. I have more than a few times had ASP.NET yell at me about mixing and matching these two across languages.


Visual Basic .NET branch_if_elseif_vb.aspx
    dim i as integer  i=12  if i = 11 then      OurLabel.Text = "It matched the 11 branch"  elseif i = 12 then      OurLabel.Text = "It matched the 12 branch"  else      OurLabel.Text = "It didn't match"  end if 
C# branch_if_elseif_cs.aspx
int i;  i = 12;  if (i == 11){      OurLabel.Text = "It matched the 11 branch";  }else if(i == 12){      OurLabel.Text = "It matched the 12 branch";  }else{      OurLabel.Text = "It didn't match";  } 

This branching structure would execute the middle elseif/else if branch because i = 12.

If statements can contain any code inside a branch that is operable in the programming language you are using. You can conditionally run code, write, or a host of other things with the branches of if statements. You can even have nested if statements in your if statements. Believe it or not, you can have nested if statements in your nested if statements that are in your if statements. I know it may be hard to believe but you can have nested if statements…and on and on. You get the point. I'll demonstrate a bunch of nested statements at the end of this section.

Now for clarity, if statements don't just check for equality, and they can also contain multiple questions in each test. Let's look at our operators for a minute so we can look out over the wild blue yonder and see that the world is our oyster when it comes to if statements and control structure as a whole.

Operators

Let's simplify this right from the start. Operators are something you started to learn about in the second grade.

Remember when…Enter dream sequence:

Miss Applebee: "Susie, I've got two blocks and you have three. Do you have more blocks than me?"

Peter: "Ooo, Ooo, Ooo!!! Miss Applebee, I know, I know!" says Peter with much excitement.

Miss Applebee: "Hush child!!! You're speaking out of turn for the third time today."

(Peter slumps in his seat. Feeling dejected, he swears he'll never open his mouth again to utter even a single peep. He will forever deprive the world of his great wisdom.)

Susie: "I have more blocks than you, Miss Applebee, because 3 is greater than 2."

Miss Applebee: "Good! That's correct."

Peter (muttering): "I knew that!!"

Miss Applebee: "Now. If I have 7 blocks and you have 4, do you have more blocks than me?"

Peter: "Ooo, Ooo, Ooo!!! Miss Applebee, I know, I know!"

Miss Applebee: "Okay Peter, what do you think?"

Peter: "4 is less than 7, so…"

Exit dream sequence.

As you can see, operators are nothing more than simple comparison tools you can use in your code. You'll see that branching and control structure is full of comparison operators. Table 3.7 lists the most common and basic operators.

Table 3.7. Operators

Visual Basic .NET

C#

Explanation

=

==

Boolean Equality (True or False)

=

=

Equality

<>

!=

Inequality

<

<

var1 less than var2

>

>

var1 greater than var2

<=

<=

var1 less than or equal to var2

>=

>=

var1 greater than or equal to var2

OR

OR

Provides for multiple comparisons such as (var1 = var2 OR var3 = var4); this returns true if either statement is true

AND

AND

Provides for multiple comparisons such as (var1 = var2 AND var3 = var4); this returns true only if both statements are true

These operators provide a full palette of colors you can use to paint your code and get what you want out of your web applications. We will be exploring the use of these throughout the rest of this chapter (and the rest of the book, for that matter).

Select/switch

Select and switch statements are the same animal, with the Select Case statement being used in Visual Basic .NET and switch being used in C#.

This branching statement is used in a similar way to the if statements, except it requires a whole lot less code. You will see the power of Select/switch statements immediately in their capability to test multiple values.

Let's try comparing a variable to days of the week using the if/elseif statements first so you have something to compare your select statement against.

Visual Basic .NET
dim WeekDay,OurString as String  WeekDay = "Tuesday"  OurString = "This day of the week is "  If Weekday = "Monday" then  OurString += "the first day of the work week"  elseif Weekday = "Tuesday" then  OurString += "the second day of the work week"  elseif Weekday = "Wednesday" then  OurString += "the third day of the work week"  elseif Weekday = "Thursday" then  OurString += "the fourth day of the work week"  elseif Weekday = "Friday" then  OurString += "the last day of the work week"  else  OurString += "on the weekend"  End If  OurLabel.Text = Ourstring 
C#
String WeekDay,OurString;  WeekDay = "Tuesday";  OurString = "This day of the week is ";  if (Weekday == "Monday"){      OurString += "the first day of the work week";  }else if(WeekDay == "Tuesday"){      OurString += "the second day of the work week";  }else if(WeekDay == "Wednesday"){      OurString += "the third day of the work week";  }else if(WeekDay == "Thursday"){      OurString += "the fourth day of the work week";  }else if(WeekDay == "Friday"){      OurString += "the last day of the work week";  }else{      OurString += "on the weekend";  }  OurLabel.Text = OurString; 

Pretty wordy for a simple statement to check what day of the week a Weekday variable matches. Now look at an example of how the Select or switch statement code for this similar function looks.

Visual Basic .NET select_days_vb.aspx
dim WeekDay,OurString as String  WeekDay = "Tuesday"  OurString = "This day of the week is"  Select Case Weekday      Case "Monday"      OurString += "the first day of the work week"      Case "Tuesday"      OurString += "the second day of the work week"      Case "Wednesday"      OurString += "the third day of the work week"      Case "Thursday"      OurString += "the fourth day of the work week"      Case "Friday"      OurString += "the last day of the work week"      Case Else      OurString += "on the weekend"  End Select  OurLabel.Text = Ourstring 
C# switch_days_cs.aspx
String WeekDay,OurString;  WeekDay = "Tuesday";  OurString = "This day of the week is ";  switch(WeekDay){      case "Monday":      OurString += "the first day of the work week";      break;      case "Tuesday":      OurString += "the second day of the work week";      break;      case "Wednesday":      OurString += "the third day of the work week";      break;      case "Thursday":      OurString += "the fourth day of the work week";      break;      case "Friday":      OurString += "the last day of the work week";      break;      default:      OurString += "on the weekend";      break;  }  OurLabel.Text = OurString; 

Look at Figure 3.8 to see the results.

Figure 3.8. The Select statement in Visual Basic .NET and the switch statement in C# are a clean way of making multiple comparisons.
graphics/03fig08.gif

When you look at this code, you can see that it is a lot cleaner than the redundant elseif and else if statements. And as my old pappy use to say, "Cleaner is better." My mom used to say this about my room when I was young. I didn't think it really applied, but it definitely applies to code.

This branching statement is an area where there is a degree of separation between Visual Basic .NET and C#, and the pickiness of C# become a bit more evident (to me, at least).

The Visual Basic .NET Select statement flows from top to bottom, checking to see whether each case in the statement is true or not and executing each branch that returns true. Pretty simple.

C# is a bit less forgiving. C# does not "fall through" to the next switch section by default. You must explicitly tell C# what behavior you want the switch to do if that particular branch returns true. You will find that you generally will use the break statement, which causes the switch to jump to the next block of code after the full case statement. For instance:

C#
String WeekDay,OurString;  WeekDay = "Monday";  OurString = "This day of the week is ";  switch(WeekDay){     //This branch would return true      case "Monday":      OurString += "the first day of the work week";      //This break would execute the end of the switch      break;      case "Tuesday":      OurString += "the second day of the work week";      break;  }  //The break would move us to this point to follow executing code after the switch 

The break provides a way to exit the switch and proceed processing code. There are two other ways to end a switch section or each case of a switch statement. They are the goto statement and the return statement. I would recommend that you consult the .NET Framework SDK (Software Development Kit) Documentation to learn more about the goto and return statements. These topics are a bit too broad to cover here and apply to things other than the switch statement.

Note

The .NET Framework SDK Documentation is the full master cookbook for the .NET Framework. It will be available on your machine if you've done a full installation of the .NET Framework. This doesn't come with the redistributable version of the .NET Framework. The .NET Framework SDK Documentation is a very powerful and extremely thorough help center for the entire .NET Framework. I would suggest you go there first when you are stumbling or struggling with any issue surrounding .NET. It usually can be found on the Start Menu in Programs > Microsoft .NET Framework SDK > Documentation on the machine on which the .NET Framework is installed. It has a full Contents, Index, and Search of the SDK documentation and is quite an impressive collection of information, examples, code samples, language references and tutorials.

There will be times throughout the book that I will also provide direct links to documents in the SDK. Just pop them in a browser address bar on the machine that has the SDK installed and it will take you directly to the page I have referenced.


Both Visual Basic .NET and C# provide ways for you to check for multiple conditions in a single Select Case branch or switch section. Again be careful to notice the differences in the way that these are performed in the different languages.

Visual Basic .NET select_days_multivarialbes_vb.aspx
dim WeekDay,OurString as String  WeekDay = "Tuesday"  OurString = "This day of the week is "  Select Case Weekday      Case "Monday","Tuesday","Wednesday","Thursday","Friday"      OurString += "during the work week"      Case "Saturday","Sunday"      OurString += "on the weekend"  End Select  OurLabel.Text = OurString 
C# switch_days_multivarialbes_cs.aspx
String WeekDay,OurString;  WeekDay = "Tuesday";  OurString = "This day of the week is ";  switch(WeekDay){      case "Monday":      case "Tuesday":      case "Wednesday":      case "Thursday":      case "Friday":      OurString += "during the work week";      break;      case "Saturday":      case "Sunday":      OurString += "on the weekend";      break;  }  OurLabel.Text = OurString; 

You can see the results in Figure 3.9:

Figure 3.9. Checking across multiple conditions is a useful way to create clean code from what would be a complicated If statement.
graphics/03fig09.gif

Visual Basic .NET allows you to place multiple conditions on the same line, separated by commas, where C# requires you to trail multiple case statements that do "fall through" until an executable piece of code is reached. Again, this must be followed by a break statement to escape the switch.

Now try to imagine producing this same branch using the if statement. The opening if would look something like this:

Visual Basic .NET
if WeekDay = "Monday" or Weekday = "Tuesday" or Weekday = "Wednesday" or Weekday =  graphics/ccc.gif"Thursday" or Weekday = "Friday" then      OurString += "during the work week"  elseif WeekDay = "Saturday" or Weekday = "Sunday" then      OurString += "on the weekend"  end if 
C#
if (WeekDay = "Monday" or Weekday = "Tuesday" or Weekday = "Wednesday" or Weekday =  graphics/ccc.gif"Thursday" or Weekday = "Friday"){      OurString += "during the work week";  }else if (WeekDay = "Saturday" or Weekday = "Sunday"){      OurString += "on the weekend";  } 

YUCK!!! You can see how much simpler a select or switch statement is.

Visual Basic .NET also provides two key words that help us expand the functionality of Select statements. They are To and Is. In Select statements, they expand the possible comparisons we can do. The To operator allows us to use these (=, <>, <, <=, >, or >=) operators. So each comparison must fit into one of the following forms:

  • expression

  • expression To expression

  • Is (operator) expression

The first one you've seen in the Select examples already. It's just a value to match against. Let's take a look at the remaining two in action.

Visual Basic .NET select_operators_vb.aspx
dim myInt as Integer  dim OurString as String  myInt = 7  OurString = ""  Select Case myInt      Case 1 To 10      OurString += "My number is between 1 and 10 <br>"      Case Is >= 11      OurString += "My number is greater than 10<br>"  End Select  OurLabel.Text = OurString 

Figure 3.10 shows the results of these great additional operators that Visual Basic .NET provides.

Figure 3.10. Visual Basic .NET provides some additional functionality in the Select statement with the To and Is keyword.
graphics/03fig10.gif

Can you see how this has expanded the function of the Select Case statement? The first case is the equivalent of either 10 separate case statements (case 1, case 2, and so on) or case 1,2,3,4,5,6,7,8,9,10. You can see again how this creates possibilities to clean up your statements to another level. These can also can have multiple expressions per case statement as well.

These keywords can also be used in string expressions as well. Again I would refer you to the SDK where you can find out more information about this. Place the following link in a web browser's address line:

ms-help://MS.NETFrameworkSDK/vblr7net/html/vastmSelectCase.htm

We must deal with one more quick issue regarding Select and switch statements. They are case sensitive and this could create some problems when comparing strings. If your case branch contains the word "Flower," but you try to compare "flower," your branch doesn't execute. You might think a solution would be to put a branch for "Flower" and "flower," but what if this value comes from a text box on a web page and the person has Caps Lock on? Then you'd also need to test for "fLOWER" and "FLOWER". The combinations are virtually endless.

"Bah, Humbug!" you may be thinking. Select and switch statements are going to be a pain. Not so fast, (Insert your Name)!!! Have you forgotten already? The String class has the ToLower() method, and it will work perfectly here. Watch!

Visual Basic .NET select_tolower_vb.aspx
dim messString,OurString as String  messString ="FloWeR"  OurString = ""  Select Case messString.ToLower()      Case "flower"      OurString += "It matched the lower case flower"      Case "FloWeR"      OurString += "It matched our wacky case FloWeR"  End Select  OurLabel.Text = OurString 
C# switch_tolower_cs.aspx
String messString,OurString;  messString = "FloWeR";  OurString = "";  switch(messString.ToLower()){     case "flower":      OurString += "It matched the lower case flower";      break;      case "FloWeR":      OurString += "It matched our wacky case FloWeR";      break;  }  OurLabel.Text = OurString; 

We can see in Figure 3.11 how using the ToLower() method allows us to force uniform comparisons.

Figure 3.11. Using the ToLower() method to force strings to lowercase makes matching expressions in Select and switch statements a breeze.
graphics/03fig11.gif

We've covered a lot of basic information with regard to branching, and I'm sure you can see how this is going to be a key for you in creating applications that perform the way you want.

Think back to the example where I said that ASP.NET is like a car, but that you need fuel to drive and steer the car, and scripting is that fuel and steering device. You might be beginning to see how you use scripting to fuel and steer your applications where we want them to go.

Looping

Just like branching statements, looping statements have parallels to our everyday lives. We loop whenever we need to do repetitive tasks a certain number of times.

Take sending holiday cards. Picture the stack of 100 envelopes, containing holiday greetings for your friends and family. To make sure that each of your friends and family members gets a card (and doesn't have an excuse to be mad at you), you must look up the address in your handy-dandy phone book, write that on the envelope, place a stamp on the envelope, lick and seal the envelope, and then place it on the "done" pile. Now go back to the stack and do it all over again and again and again till your stack is gone and your "done" pile is 100 envelopes tall.

You just looped through your holiday cards. Looping in programming is no different. Repetitive processes are performed over and over until all the items have been processed according to the loop's conditions.

The loops that are available in Visual Basic .NET and C# can be grouped into two different types. The first group is the for loop. for loops run through a certain number of times.

The second group is made up of two different types of loops that have different names in the two languages. The first type is called Do Until in Visual Basic .NET and do in C#. The second is called Do While in Visual Basic .NET and while in C#. Both types of loops continue until a condition is met, just like when the pile of holiday cards is finished. The only difference between the two types is when the test for the condition is performed.

  • Do Until/do. The code inside the loop is executed, and then the test is performed. If the condition returns false, the loop is executed again.

  • Do While/while. The condition is checked before the code is ever executed. If it returns true, the loop is executed, and then returned to be tested again.

These concepts may be a bit difficult to wrap your brain around right now while they're just being explained in words, but after you see them in action they will make perfect sense.

for Loops

Like I said earlier, for loops run a certain number of times. This number can be determined in just about any way that you can create a numbered expression. For instance:

Visual Basic .NET loop_for_simple_vb.aspx
dim i as Integer  for i=1 to 5      OurLabel.Text += "This is line number " + i.ToString() + " in our loop.<br>"  next 
C# loop_for_simple_cs.aspx
int i;  for(i = 1;i <= 5;++i){      OurLabel.Text += "This is line number " + i.ToString() + " in our loop.<br>";  } 

You can see the results in Figure 3.12.

Figure 3.12. for loops help you go through repetitive blocks of code in a controlled fashion.
graphics/03fig12.gif

What you'll notice right away about the two different languages' interpretation of the condition statement is that Visual Basic .NET seems to make one sweeping statement, i=1 to 5, and C#'s statement is broken into three sections separated by semicolons (i=1;i >= 5; ++i).

Actually, all three elements present in C# are also present in Visual Basic .NET; they are just not as apparent. It's easier if you understand the C# example first and work back to Visual Basic .NET after that.

The first statement, i = 1, is the initialization of the i variable. This is a nice thing about for loops they save an extra line of code for initialization. Not a big deal, but it's nice. The second statement, i <= 5, is pretty familiar in its use of the "less than or equal to" operator. This second segment controls the condition of the for loop. Last is a strange-looking fellow, ++i, which is simply a shortcut that adds 1 to the value of i. Its longhand equivalent would be i=i+1. It is called an increment operator. Of course it has a counterpart that is called…Anyone? Right!! A decrement operator. BIG WORDS, look out!!

Although you've gone over a bunch of operators in this chapter, you can dig a whole lot deeper in the SDK. The following are URLs for the operator section for both Visual Basic .NET and C#.

  • Visual Basic .NET: ms-help://MS.NETFrameworkSDK/vblr7net/html/vagrpOperatorSummary.htm

  • C#: ms-help://MS.NETFrameworkSDK/csref/html/vclrfcsharpoperators.htm

The Visual Basic .NET version of the for loop also has all these as well. Two are bunched together and one is assumed by default. The declaration of the variable is highlighted in bold in the following line of code.

 for i=1 to 5 

The condition statement is in there, too, and is basically made up of the whole statement highlighted in bold as follows:

 for i = 1 to 5 

After the variable is set, we are looping from the variable's value, or 1 in this case, to 5. Notice the use of the word to in the statement. Remember to from the Select statements earlier in this chapter? The keyword to in Visual Basic .NET can be likened to the word "span." From here 'To' there. Or, in other words, carry on this function across this span of numbers. The question then becomes, how do you get across these numbers, or move from 1 to 5? C# had the blessed Increment operator to do this for you. How does Visual Basic .NET magically do this?

Well, Visual Basic .NET doesn't do magic. This loop has a default counter built into it that automatically increments the value of the counter by 1 each time through the loop. Great for knuckleheads like me that have more than once forgotten to increment loops and have sent a page into an infinite loop until the web server came crashing down. Whoops!

But are you stuck with single digit increments? Hardly! You can do whatever you want in your loops with regard to incrementing numbers. The mysteriously hidden default incrementor is a keyword called Step. Let's look at a for loop with different incrementing values to see how this is done.

Visual Basic .NET loop_for_increment_vb.aspx
dim i as Integer  for i=1 to 10 Step 2  OurLabel.Text += "Odd Numbers: " + i.ToString() + "<br>"  next  OurLabel.Text += "<br><br>"  for i=2 to 10 Step 2  OurLabel.Text += "Even Numbers: " + i.ToString() + "<br>"  next  OurLabel.Text += "<br><br>"  for i=3 to 10 Step 3  OurLabel.Text += "Multiples of 3: " + i.ToString() + "<br>"  next 
C# loop_for_increment_cs.aspx
int i;  for(i = 1;i <= 10;i += 2){      OurLabel.Text += "Odd Numbers: " + i.ToString() + "<br>";  }  OurLabel.Text += "<br><br>";  for(i = 2;i <= 10;i += 2){      OurLabel.Text += "Even Numbers: " + i.ToString() + "<br>";  }  OurLabel.Text += "<br><br>";  for(i = 3;i <= 10;i += 3){      OurLabel.Text += "Multiples of 3: " + i.ToString() + "<br>";  } 

You can see the results of this code in a browser in Figure 3.13.

Figure 3.13. for loops can increment in just about any way you can imagine.
graphics/03fig13.gif

As you can see, the first two examples are incremented by 2 each time through the loop until the condition of <= 10 is met. The third example increments by 3 until the condition of <= 10 is met.

You use the Step keyword to add value to your variable each time through the loop in Visual Basic .NET, and in C# you simply use the shortcut operator that adds the value following the += sign to the current value of i.

The Step keyword or the operation of the for loop isn't limited to addition. You can count down, as well, by setting the step value to a negative number in Visual Basic .NET or by using the -- operator in C#.

Visual Basic .NET loop_for_decrement_vb.aspx
dim i as Integer  for i=5 to 1    Step -1      OurLabel.Text += "Countdown: " + i.ToString() + "<br>"  next 
C# loop_for_decrement_cs.aspx
int i;  for(i = 5;i >= 1;--i){      OurLabel.Text += "Countdown: " + i.ToString() + "<br>";  } 

As you can see in Figure 3.14, you aren't limited to just addition; you can do subtraction as well. Now let's move on to a smart for loop that knows how many times to loop without ever being told.

Figure 3.14. And now for something completely different… Backward looping!
graphics/03fig14.gif
for each/foreach Loops

for each type loops are just like for loops in the previous section in that they go through the loop a specific number of times, but you don't predetermine that number and enter it yourself. It is determined by the number of elements in an array of information.

You'll learn more about arrays later in the book, but for the sake of these examples I'll just say that an array is a variable that can hold multiple values that are identified by an index number. Huh? Not bad for a brief explanation.

So the for each loop is pretty easy to understand if you just think of it in plain English. Execute the loop for each element in the multi-value variable (array). Take a look:

Visual Basic .NET loop_for_each_vb.aspx
dim Beatles(3) as String  dim eachBeatle as String  Beatles(0) = "John Lennon"  Beatles(1) = "Paul McCartney"  Beatles(2) = "George Harrison"  Beatles(3) = "Ringo Starr"  OurLabel.Text = "<u><b>The Beatles</b></u><br>"  for each eachBeatle In Beatles      OurLabel.Text += eachBeatle + "<br>"  next 
C# loop_for_each_cs.aspx
string[] Beatles = new string[4];  Beatles[0] = "John Lennon";  Beatles[1] = "Paul McCartney";  Beatles[2] = "George Harrison";  Beatles[3] = "Ringo Starr";  OurLabel.Text = "<u><b>The Beatles</b></u><br>";  foreach (string eachBeatle in Beatles){      OurLabel.Text += eachBeatle + "<br>";  } 

Look at all the Beatles gathered together in Figure 3.15.

Figure 3.15. for each/foreach loops enable you to just feed an array of data into a loop and, wiz-bing-bang, it knows how many times to go through the loop like magic.
graphics/03fig15.gif

"Pay no attention to that array behind the curtain!!!" I mean, try not to get hung up wanting to understand arrays now. You're trying to understand the for each loop here, not the array. The first time through the loop, it sets the value of eachBeatle, which is a string variable, to the first value in the array, which is Beatles(0) or John Lennon. Then you write the eachBeatle to the page using the Response.Write() method and proceed to the end of the loop, which shoots you to the top again and moves you forward to the next element in the Beatles() array. Then the process starts all over again and proceeds to do this for each element in our array. Get it? Got it? Good!!

Do Until/do Loops

You use this type of loop when you want something to happen until something else happens, and you know the first something needs to happen at least once before the second something can even possibly happen. Whew! Now I'm confused.

In other (and more understandable) words, you want the loop to execute at least once before the condition that causes you to exit the loop is met.

For a hypothetical example, imagine you have a piggy bank with $10 dollars in it, and you know you can put $45 a week into the piggy bank. You are shooting for $500 dollars in the piggy. You want to know how many weeks it will take and what your piggy bank will contain each week. You know if you cracked her open now she'd have $10 in her, and this is less than your goal, so you must run through your code at least once to exceed your value. This is what this do until/do loop would look like:

Visual Basic .NET loop_do_until_vb.aspx
dim Piggy,Deposit,Goal,Week as integer  Piggy = 10  Deposit = 45  Goal = 500  Week = 0  OurLabel.Text = "<u><b>Our Piggy Bank</b></u><br>"  OurLabel.Text += "Opening Balance: " + Piggy.ToString() + "<br>"  Do Until Piggy > Goal      Piggy += Deposit      Week +=1      OurLabel.Text += "Week# " + Week.ToString() + " Piggy's Balance: $" + Piggy.ToString( graphics/ccc.gif) + "<br>"  Loop  OurLabel.Text += "<br>It will take " + Week.ToString() + " weeks to reach our goal." 
C# loop_do_until_cs.aspx
int Piggy,Deposit,Goal,Week;  Piggy = 10;  Deposit = 45;  Goal = 500;  Week = 0;  OurLabel.Text = "<u><b>Our Piggy Bank</b></u><br>";  OurLabel.Text += "Opening Balance: " + Piggy.ToString() + "<br>";  do{      Piggy += Deposit;      ++Week;      OurLabel.Text += "Week# " + Week.ToString() + " Piggy's Balance: $" + Piggy.ToString( graphics/ccc.gif) + "<br>";  }  while (Piggy < Goal);  OurLabel.Text += "<br>It will take " + Week.ToString() + " weeks to reach our goal."; 

Again, you need to concentrate. Now look into my eyes. You are getting loopy…loopy…loopy.

Now that you are as loopy as I am, you can dissect the loops shown in Figure 3.16. Remember that this type of loop always executes once before the condition is checked. This is much more apparent when you look at the code in the C# example, because the condition is actually after the code that you want to execute. Visual Basic .NET's way of doing this is a bit deceiving, because the conditions of the loop aren't really executed where they are. They are actually executed by the keyword loop. When you look at it this way, the conditions don't execute until the loop statement, even though they are at the top of the statement.

Figure 3.16. The Do Until/do loop executes the code inside the loop at least once, then checks the condition to see whether it's true.
graphics/03fig16.gif

Also take notice that C# uses the keyword while at the end of the loop, which changes how the statement is evaluated. In Visual Basic .NET, you ask it to "Do this until piggy is greater than $500," and then stop. You're checking to see whether piggy is greater than $500. The while statement requires you to evaluate this differently. C# says, "Continue do this while piggy is less than $500," and then stop. You are checking to see whether piggy is still less than $500.

As you examine this code, you can see things inside the loop happen like this:

  1. Piggy gets her deposit.

  2. You increment the week so that you can keep track of what week you're on and how many weeks it takes.

  3. Write to the page the week you're on and what that week's balance is.

Now this do-type loop that always executes once is just fabulous if you know that you want to execute your loop at least once. You might use it, for instance, to see how many times through a loop it would take to pick a specific name out of a random list of names. You know that the answer can't be 0 because no name can be randomly picked if the loop never executes.

But what if you take your loop from the piggy bank example and already have $505 in piggy? If you use this do-type loop that always executes at least once, you'll be depositing money unnecessarily into piggy during the first loop. What do you do? You don't want to overstuff piggy!! Enter the Do While/while loop.

Do While/while Loops

This type of loop makes it possible to protect piggy's gorgeous figure and prevents her from getting overstuffed because it checks her condition before a deposit is made, or more seriously, before the loop ever executes.

We are also going to add an if statement to the bottom of this code to check whether a deposit was made and to display what happened depending on these conditions.

Take a look:

Visual Basic .NET loop_do_while_vb.aspx
dim Piggy,Deposit,Goal,Week as integer  Piggy = 505  Deposit = 45  Goal = 500  Week = 0  OurLabel.Text += "<u><b>Our Piggy Bank</b></u><br>"  OurLabel.Text += "Opening Balance: " + Piggy.ToString() + "<br>"  Do While Piggy < Goal      Piggy += Deposit      Week +=1      OurLabel.Text += "Week# " + Week.ToString() + " Piggy's Balance: $" + Piggy.ToString( graphics/ccc.gif) + "<br>"  Loop  if Week <> 0 then      OurLabel.Text += "<br>It will take " + Week.ToString() + " weeks to reach our goal."  else      OurLabel.Text += "Piggy's balance already exceeds our goal. Whahooey!!"  end if 
C# loop_do_while_cs.aspx
int Piggy,Deposit,Goal,Week;  Piggy = 505;  Deposit = 45;  Goal = 500;  Week = 0;  OurLabel.Text += "<u><b>Our Piggy Bank</b></u><br>";  OurLabel.Text += "Opening Balance: " + Piggy.ToString() + "<br>";  while (Piggy < Goal){      Piggy += Deposit;      ++Week;      OurLabel.Text += "Week# " + Week.ToString() + " Piggy's Balance: $" + Piggy.ToString( graphics/ccc.gif) + "<br>";  }  if (Week != 0){     OurLabel.Text += "<br>It will take " + Week.ToString() + " weeks to reach our goal.";  }else{     OurLabel.Text += "Piggy's balance already exceeds our goal. Whahooey!!";  } 

Survey says…For the number one answer, see Figure 3.17.

Figure 3.17. The Do While/while loop checks whether the condition is true before it executes the code inside the loop.
graphics/03fig17.gif

Thank goodness we have these types of loops. Piggy will live to see another day because a deposit was averted. The Do While/while statement checked the condition to see whether piggy's balance was less than $500. Her balance was $500, and so the loop jumped to the next block of code, which was the if statement.

What would happen if piggy's beginning balance was $390 and you ran this code? You can see the results in Figure 3.18, where you are informed of what your weekly balances will be and how long it will take to fill up piggy, just as in the do until/do loop examples earlier.

Figure 3.18. When the condition calls for the code, it executes and provides the proper information.
graphics/03fig18.gif

You have been through many types of branches, including a plethora of if and looping statements. These create a bunch of tools and concepts from which you can choose to manipulate your data and code flow. What you've learned about control structure will enable you to control what your code will do under just about any condition or situation. The more you work with branches and loops, the more you can see how wide the possibilities are. Just keep playing and have fun.


   
Top


ASP. NET for Web Designers
ASP.NET for Web Designers
ISBN: 073571262X
EAN: 2147483647
Year: 2005
Pages: 94
Authors: Peter Ladka

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