IS 350 LAB 7
LOOPS AND GENERIC COLLECTIONS

Abstract

In the last lab, you worked with decisions and decision-making. In this lab, you will work with statements that execute over and over again Generally speaking, these statements are categorized as loops. In this lab you will:

  • Create different kinds of loops called pretest and posttest loops.
  • Create a special form of loop called a For loop.
  • Understand the purpose of a counter and an accumulator
  • Work with lists of objects using collections
  • Work with controls that involve loops
  • Be introduced to the DataGridView control as a means of displaying a grid of data.

This lab is divided into three parts.

  • In the first part, you will write simple loops that will count from 10 to 1.
  • In the second part, you will write increasingly complex loops so as to determine whether a number is a prime number or not.
  • In the final part of the lab, you will expand the bank account case to work with a list of accounts instead of just a single account. In the next lab, you will learn how to read and write the account list from and to the disk.

Key Terms

  • Accumulator: An accumulator is commonly used in a loop to calculate a total.
  • Collection: A collection is an object that references a list of other objects in some way. The .NET Framework supports several different collections each suited for a particular purpose.
  • Counter:A variable whose value is incremented or decremented by a constant value (often 1) each time through a loop.
  • For loop: A For loop is another form of loop used that is used when the number of loop iterations can be determined before the loop begins to execute.
  • For each loop: A specialized form of a For loop where the loop returns an object from a collection each time through theloop.
  • Generic collection: A generic collection is a collection derived from System.Collections.Generic. A generic collection stores references to multiple objects all having the same data type.
  • Infinite loop: A loop that executes forever because no condition occurs that causes the loop to terminate.
  • Pre-test loop: A pre-test loop is a form of loop where the loop’s condition is tested before the statements in the loop execute. Thus, if the loop’s condition is initially False, then the statements in the loop will never execute.
  • Post-test loop: A post-test loop is a form of loop where the loop’s condition is tested after the statements in the loop execute. Thus, the statements in a post-test loop will always execute at least once.

Lab Summary

This lab is made up of three parts.

  • In the first part, you will write simple loops so as to learn about their syntax and basic loop operations.
  • In the second part, you will write loops in different ways. All of the loops determine whether a number is prime or not.
  • In the third part of the lab, you will extend the bank account case. In this lab, you will further extend the bank account class to work with a list of bank accounts. In the next lab, you will see how to save the data to disk and read it from the disk.

Introduction to Loops

The loop is the third programming structure after the decision-making and sequence structures. Loops are designed to execute a block of statements repeatedly until a condition becomes true or while a condition is true. Loops are categorized into two types: pre-test and post-test loops.

  • Using a pre-test loop, the loop’s condition is tested before executing the loop’s statement block. Thus, using a pre-test loop, the loop’s statement block might never execute.
  • Using a post-test loop, the loops condition is tested after executing the statement block. Using a post-test loop, the loop’s statement block will always execute at least once.

Visual Basic supports various forms of pre-test and post-test loops.

  • The While/ EndWhileloop is a pre-test loop. The statement block in the loop executes while the condition is True.
  • The DoWhile/ Loop block is also a pre-test loop. It works exactly the same way as the While / EndWhile block.
  • The Do Until / Loop block is also a pre-test loop. However, the loop’s statement block executes until a condition becomes true, instead of while a condition is true.
  • The Do / Loop While block is a post-test loop. The condition is tested after the loop has executed the first time. Thus, the loop’s statement block will always execute at least once.

Take a look at the following loop portal

In the following examples, you will write and debug simple loops that will count down from 10 to 1.You will write these loops as both pre-test and post-test loops.

The While/ End Whileloop is shown in the following statement block:

Dim Counter1 As Integer = 10

While (Counter1 >= 1)

Console.WriteLine(Counter1.ToString())

Counter1 -= 1

End While

  • The While/ End Whileloop is a pre-test loop.
  • The loop block is marked by the While and EndWhile statements.
  • The loop’s condition follows the While keyword. The condition must evaluate to a Boolean value, just as the condition in a decision-making statement must evaluate to a Boolean value.
  • In the above example, the first time through the loop, 10 is greater than or equal to 1, so the loop’s statements execute. The value of the variable Counter1 is printed to the Output window, and then the variable is decremented by 1. The process continues while the variable Counter1 is greater than or equal to 1.

The Do While / Loop works just like the While / End While loop. Visual Basic’s syntax has evolved over the years, so there are a couple of ways to accomplish an identical task.

Do While (Counter1 >= 1)

Console.WriteLine(Counter1.ToString())

Counter1 -= 1

Loop

The above loop executes the statement block while Counter1 is greater than or equal 1. The loop is a pre-test loop.

The Do Until / Loop statement operates similar to the Do While / Loop statement. However, the loop executes until a condition becomes true instead of while a condition is true.

Do Until (Counter1 < 1)

Console.WriteLine(Counter1.ToString())

Counter1 -= 1

Loop

  • The Do Until / Loop block is also a pretest loop. Basically, the condition in a Do Until loop is reversed compared to the condition in a Do While loop.
  • The above loop executes until the variable Counter1 is less than 1.
  • Each time through the loop the variable Counter1 is decremented by 1.

The following two loops types of loops are post-test loops. That is, the loop’s condition is tested after the loop’s statement block has executed at least once.

Do
Console.WriteLine(Counter1.ToString())
Counter1 -= 1
Loop While (Counter1 >= 1)

  • The Do / Loop While loop executes statements while a condition is true. In this example, the statement block executes while Counter1 is greater than or equal to 1. The condition is not tested until the statement block has executed the first time.
  • Statement block writes the variable Counter1, and then decrements the variable.

The Do / Loop Until loop executes statements until a condition becomes true. Thus, the expression in the condition is reversed.

Do
Console.WriteLine(Counter1.ToString())
Counter1 -= 1
Loop Until (Counter1 < 1)

The preceding statement examples show the simplest of loops. Loops can be much more complex. For example:

  • Loops can contain decision-making statements.
  • Loops can contain other loops.
  • Loops can contain both nested loops and decision-making statements, which in turn can contain other loops and decision making statements.

As you progress through this and other labs, you will continue to work with more complex loops.

Hands-on steps: Understanding loop syntax:

In the following steps, you will write several loops and examine their execution path using the same debugging tools that you have been using.

  1. Start Visual Studio and create a new project. Call the project FirstLoop.
  2. Create a button on the form. Name the button btnLoop1. Enter the following code in the button’s Click() event hander:

Dim Counter1 As Integer = 10

While (Counter1 >= 1)

Console.WriteLine(Counter1.ToString())

Counter1 -= 1

End While

  1. Run the program. Click the button.
    The following output should be displayed to the Output window. Remember, to view the Output window, click Debug, Windows, Output.

Debugging Loops

The debugging tools can be very useful when working with loops. First, you can single-step through the statements in a loop watching it execute. When loops iterate thousands or millions of times, single-stepping through the loop is not practical. In these situations, you can create what are called hit count breakpoints or conditional breakpoints.

In the following exercise, you will use the debugging tools to watch the loop that you just wrote iterate.

Hands-on Steps: Debugging loops

  1. Set a breakpoint on the following statement:

While (Counter1 >= 1)

  1. Start debugging the program and click the button you just created. The breakpoint should be hit and highlighted as usual.
  2. ClickDebug, Windows, Watch, Watch1 to display the first Watch window. In the Name column, enter the Counter1 (the loop’s condition variable). Its value should be 10 initially as shown in the following figure:

  3. Single Step through the program by pressing F11 or pressing the StepInto button. As you step through the loop, you should see the variable Counter1 being decremented by 1, the EndWhile statement reached, and the loop’s condition again and again. Looking at the Watch window, pay attention to the variable Counter1 being decremented by 1 each time through the loop. Continue to press F11 until the loop ends (Counter < 1)

As you can see, the debugging tools allow you to watch a loop iterate. However, imagine that the loop iterated thousands of times instead of just 10. Single stepping through a loop would not be practical. In these cases, you can use specialized breakpoints called hit count breakpoints and conditional breakpoints.

  • A hit count breakpoint suspends execution only after a loop has iterated some number of times.
  • A conditional breakpoint suspends execution when a particular condition becomes true or false.

If you view the Breakpoints window at this point, you will see the breakpoint line, that there is (no condition), and the breakpoint will suspend execution each and every time the breakpoint is hit (break always.

In the following steps, you will learn how to change a breakpoint’s behavior to operate as a conditional and hit count breakpoint.

Note that the developer interface to work with conditional and hit count breakpoints has changed considerably with the most recent versions of Visual Studio.

Hands-on Steps: Creating conditional and hit count breakpoints.

So far in the preceding lab, you have written a loop that counts from 10 to 1. Suppose that you were counting from 10000 to 1. Clearly, it would be impractical to single step through the loop 10000 times. When a loop has an error, those errors often stem from an error that causes the loop to terminate. So in a loop that counts from 10000 to 1, you are not interested in all 10000 iterations, you are only interested in the last couple.

To customize a breakpoint, you can right-click on the Breakpoint in the Code Editor, and then click Conditions… You can also select the breakpoint in the Breakpoints window. Right click and select Settings.

  1. Modify the code that declares the variable Counter1 so that its initial value is 10000.
  2. In the Code Editor, right click on the maroon circle marking the breakpoint line, and then click Conditions to display the following dialog box. (Your line numbers might differ)

  3. By default, the Conditions check box should be checked. If it is not, check it. In the first combo box, select Hit Count. In the second combo box, select the equal sign (=). In the last box, select 9998. Here you are telling the system to break only after the breakpoint has been hit 9998 times.

  4. Make sure that the output window is visible.
  5. Run the program again. You will see the numbers count from 10000 to 4.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

Dim Counter1 As Integer = 10000

While (Counter1 >= 1)

Console.WriteLine(Counter1.ToString())

Counter1 -= 1

End While

There are a few common problems that arise when working with loops.

  • You write a loop that never exits called an infinite loop.
  • When working with arrays (discussed in the next lab), you miss examining an item in the array or try to examine an item that does not exist. This same problem occurs with collections.

The following code segment shows in infinite loop:

Dim x As Integer = 1

Dim IterationCount As Integer

Do While (x < 10)

x = 1

IterationCount += 1

Loop

The above code will run forever because the value of x is always less than to 10.

Hands-on Steps: Debugging loops.

  1. Create a button on the form named btnInfiniteLoop and write the following statements in the button’s Click() event handler.
  2. Again, these statements represent an infinite loop. Run the program. Because this is an infinite loop, the loop’s statements run forever. You cannot interact with the form’s controls. Run the program. Click the Infinite loop button. If you let the program run for a few seconds, it will throw a numeric overflow exception because the variable IterationCount exceeds the maximum value for an Integer.

  3. End the program.
  4. Run the program again. Quickly, click the Pause button on the Debug toolbar. Execution is suspended. You can see that that execution is suspended in the loop.

  5. End the program.

Developing Pre-test and Post-test loops

In this lab section, you will learn how to develop different forms of loops. You will write three different procedures that will determine whether or not a number is a prime number. Each procedure accomplishes the same thing. It is just written a bit differently. The procedure you will write will determine whether a number, passed as an argument, is a prime number. As you should recall, a prime number is a whole number which is divisible only be one and itself. The logic of this program is as follows:

  • Initialize a counter to two (2).
  • Initialize a Boolean flag to True.
  • Create a loop that will iterate from 2, to the tested number / 2. Call this counter.
  • In the loop, use an If statement to test whether the number is evenly divisible by the counter’s value (Number Mod Counter = 0).
  • If it is, set the flag to False and exit the loop. The number is not prime.
  • If it is not, increment the counter and test the loop’s condition again.

Note that there are more efficient algorithms to determine whether or not a number is prime. These algorithms are beyond the scope of this chapter.

HANDS-ON STEP: Writing pre-test and post-test loops

  1. Create a new project named IS350LoopLab. In the project, create a Module named Prime.
  2. Create the following procedure named IsPrimeWhile() in the above Module block.

Public Shared Function IsPrimeWhile(Number As Integer) As Boolean

Dim Counter As Integer = 2

Dim PrimeFlag As Boolean = True

While ((Counter <= Number / 2) = True)

If (Number Mod Counter = 0) Then

PrimeFlag = False

Exit While

End If

Counter += 1

End While

Return PrimeFlag

End Function

  • The above Function procedure accepts one argument, the Number to test, and returns a Boolean.
  • The loop’s counter is initialized to two (2) instead of one (1), because we don’t want to test that the number is divisible by one. A whole number is always divisible by one.
  • The While loop contains the condition. The If test determines whether the number is not prime. If the number is determined to be not prime, then the PrimeFlag is set to False, and the While loop exits.
  • The Exit While statement a While loop to exit immediately.
  1. Create the following procedure named IsPrimeDoWhile.

Public Shared Function IsPrimeDoWhile(Number As Integer)
As Boolean

Dim Counter As Integer = 2

Dim PrimeFlag As Boolean = True

Do While ((Counter <= Number / 2))

If (Number Mod Counter = 0) Then

PrimeFlag = False

Exit Do

End If

Counter += 1

Loop

Return PrimeFlag

End Function

This code works identically to the preceding code. However, the older DoWhile / Loop syntax is used over the While / EndWhile syntax. Both loops do exactly the same thing, however. The Exit While statement is replaced by the Exit Do statement.

In the next example, you will write the loop as a post-test loop than a pre-test loop

  1. Create the following procedure named IsPrimeDoLoop.

Public Shared Function IsPrimeDoLoop(Number As Integer) As Boolean

Dim Counter As Integer = 2

Dim PrimeFlag As Boolean = True

Do

If (Number Mod Counter = 0) Then

PrimeFlag = False

Exit Do

End If

Counter += 1

Loop While ((Counter <= Number / 2) = True)

Return PrimeFlag

End Function

The above loop is implemented as a post-test loop instead of a pre-test loop, although the results are the same.
In the following sequence of steps, you will write the code to call the above procedures.

  1. On the main form, create three Button control instances named btnIsPrimeWhile, btnIsPrimeDoWhile, and btnIsPrimeDoLoop.
  2. Create a text box named txtInput and a label named lblOutput.
  3. Create Click event handlers for each of the three buttons.Enter the following statements in the btnIsPrimeWhile_Click() event handler:

PrivateSub btnIsPrimeWhile_Click(sender AsObject, e AsEventArgs) _