Back to Basics: Looping
Pretty soon after learning conditional statements comes looping. Looping can be used to scan through a recordset, or to add items to a drop down or any number of things really. Looping is vital to almost any program. Today we will learn how to use for loops and while loops in both C# and VB.For-Loop
In both C# and VB the for loop can come in two flavors. The more traditional what I will call the counting for loop, and a for each loop which will allow you to loop through a collection or enumeration of things.First we will start off with the counting for loop. There are three main parts to this for loop. First is the counter and it's initialization. You can either define this outside of the loop and just reference it in the loop, or you can define it inline with the loop. This is the the method I prefer since the scope of the variable is localized to the for loop. Traditionally the counter variables are 'i', 'j', or 'k'. There is nothing wrong with using other variable names, but you will see these 3 used all the time. More often than not you will see 'i' being the most prevalent.
The second part is the ending criteria such as an upper or lower bound, it is essentially how many times the loop will execute. This is a very important piece because if you don't have it then you will enter into an infinite loop in which there is no way your program will exit until you run out of memory or hit the upper bound of the data type you are using (both are bad things). Since this is tested at the beginning of each iteration this is called a pre-test loop.
Lastly we define how are are going to increment our counter. Many times this is just up by one each time or down by one. But you can use any increment you wish. The increment happens after the end of the loop.followed by the check of the counter. If the ending criteria is not met the loop will execute again.
In this example we are just going to loop 10 times writing out to the screen the value of i each time
C#
//Example 1You can see how I defined the variable 'i' inside the for loop in the first example. In the second I declared the variable outside of the loop. Both are valid, and it is just personal preference. Just remember that the scope on each variable is different.
for (int i = 0; i < 10; i++) {
Response.Write("i=" + i.ToString() + "<br/>");
}
//Example 2
int i;
for (i = 0; i < 10; i+=2) {
Response.Write("i=" + i.ToString() + "<br/>");
}
In the second example above we are incrementing by 2 each time through the loop. The += notation is the same thing as writing out the full expressoin i = i+2. It just makes the whole thing easier to read.
In VB.Net if you are going to increment by 1 each time around you do not need to define the last piece of the loop, it is built in. So in example 1 below we are just going to count up by one. In example 2 we will increment by 2 as before.
VB
//ExampleSo as you can see in Example 2 using the step clause in VB will allow you to change what you increment (or step) by.
For i As Integer = 0 To 10
Response.Write("i=" & i & "<br/>")
Next
//Example 2
For i As Integer = 0 To 10 Step 2
Response.Write("i=" & i & "<br/>")
Next
The next type of For loop is the for each, which is very useful in stepping though a collection of objects. For example, lets assume we have a collection, addressBook, of people using the class (person) we have been using in the past 2 posts. The examples are just going to loop through all of the items in the collection. Note how we do not have to declare a counter. .Net will handle fetching each item and knowing when to stop. This loop can be re-written into a counting for loop very easily. I would be willing to say that each foreach loop could be re-written as a counting for loop, but the reverse isn't true. I'm not positive on that, but I can't think of any examples to prove me wrong, if you can think of one put it in the comments below.
C#
foreach (person peep in addressBook) {
Response.Write(peep.LastName);
}VBFor Each peep As person In addressBookAs you can see the syntax is almost identical between the two languages.
Response.Write(peep.LastName)
Next
While Loops
While have the same purpose as a for loop, and they can be swapped in almost any case, but sometimes it just makes more sense to use a while loop instead of a for loop.For example, lets say we have a loop that we really have no way of knowing how many times the loop would need to run. A great example of this is while reading a file from disk. We want to keep looping until we hit the end of file (EOF) character. I am sure you could probably find out the length of the file, divide the bytes and use a for loop, but it just feels better to use a while loop. After programming for a while you will get a good feel of when to use a while loop and when to use a for.
The first example, is just re-writing the counting loop from above just to show you how it is done. The second example is reading from an OracleDataReader. I am not going to show the opening of the data reader and all that, but I am just going to loop through it for you and am going to fill our addressBook from before. I am going to use some newer notation (.Net 3.5) to make the code a bit shorter for the initialization of the person object.
C#
//Example 1So those are your basic loops. There is one more type of loop that can be used the do-while. But haven't used that in many years and is only used in a few cases. The difference being the compiler will check the condition at the end of the loop instead of at the beginning, so your loop will always execute at least once, this is called a post test loop.
int i;
while (i < 10) {
Response.Write("i=" + i.ToString());
i++;
}
//Example 2
while (reader.HasRows) {
person peep = new person { FirstName = reader["FirstName"], LastName = reader["LastName"], Age = reader["Age"] };
addressBook.Add(peep);
}
And a special thanks to Brent for guest editing this post
Labels: .NET, Back to Basics
posted by Tom Becker at
11/22/2009
![]()


0 Comments:
Post a Comment
<< Home