Programming Worksheet Loops and Program Control: Programming Worksheets Harjinder Singh (2009)
Programming Worksheet Loops and Program Control: Programming Worksheets Harjinder Singh (2009)
Page 1 of 17
Programming Worksheets
There are 3 (groups of) defined ways of performing looping operations in the VB.NET programming environment: For Next Do Loop While and Do While Loop Do Loop Until and Do Until Loop
In reality both varieties of the Do While and Do Until loops are very similar with subtle but important differences. This session will pick up from where the previous session left off with the idea of using conditional control statements but this time for loops. We will: define the concept of loops for repetition, look at some of the core differences between the different styles of loop that can be implemented in VB.NET, the impact that loops can have on the execution of code.
This workshop session will get you to practice programming skills using the various types of loops available in VB.NET. Please note: worksheets now no longer give specific instructions on how to create a new application project. You must refer to the previous labs to remind yourself how to do this. Just remember to select a sensible name (e.g. Loops_Lab) and location (for example, under your network drive, select your relevant Programming folder etc) for your project in the appropriate dialogue! Types of loops in VB.NET ForNext Loop: ForNext Loops are based on iterative processes which know (up-front) how many times they will execute. The syntax for a ForNext Loop uses the following formula: For Counter = Start To Finish [Step Value] Do something Next Note- the square brackets [] indicate that the code is optional and not necessary. Also Start and Finish should be of a whole number type e.g. Integer. For example;
For
Next
intCounter = 1 To 12 Step 2 intResult = intCounter * 10 lstResult.Items.Add(intCounter & " x " & 10 & " = " & intResult)
Page 2 of 17
Programming Worksheets
The graphic below illustrates the expected behaviour of the For Next loop:
A Counter variable is used to track how many times the code in a loop has been executed and must be declared as such. This counter is automatically initialised and incremented / decremented for you depending on how the loop is declared (see next point), e.g;
Dim intCounter, intResult As Integer For intCounter = 1 To 12 intResult = intCounter * 10 lstResult.Items.Add(intCounter & " x " & 10 & " = " & intResult) Next
Page 3 of 17
Programming Worksheets
The counter variables in ForNext statements can be modified to count in different stepping intervals (not just units of one) the step Value will determine the size of the steps e.g. Step 2 has the following effect;
For intCounter = 2 To 12 Step 2 intResult = intCounter * 10 lstResult.Items.Add(intCounter & " x " & 10 & " = " & intResult) Next
ForNext loops can also have counter variables that are either incremented or decremented. i.e. the step Value described in the previous point can also be positive (for incrementing) or negative (for decrementing). However, if decrementing, you will need to ensure that the order of the start and finish values is correct i.e. Start > Finish so that decrementing makes sense. E.g. -2 for going backwards in steps of 2.
For intCounter = 12 To 2 Step -2 intResult = intCounter * 10 lstResult.Items.Add(intCounter & " x " & 10 & " = " & intResult) Next
Page 4 of 17
The For Loop construct is extremely useful as it takes away the need to be checking conditions (i.e. Counter >= Start?), and incrementing / decrementing the loop counter both are done automatically. Thus it is particularly useful for iterating through collections of information such as Arrays (which we will do a worksheet on later). For situations that are not as clearly pre-defined as the one described above, a different type of loop is required where the programmer needs to take control of the condition checking and incrementing / decrementing of the loop variable. For this purpose, VB.NET provides several other loop constructs based on the Do Loop keyword construct. Most loops that use the keyword Do are generally accepted as loops that by definition do not necessarily have a definitive range over which they will run i.e. the condition to terminate the loop could occur at any time - as the condition is usually determined by a variable that is manipulated in the body of the loop. i.e. By definition, a For loop has the start and finish conditions declared that the loop SHOULD execute to the full whereas a Do Loop iterates for a non-predetermined number of times. Therefore, the Do Loop can run indefinitely or while / until a condition is met. There are 4 styles of Do Loop; they are grouped into 2 subtypes by the point of checking of the loop condition. They can be top-exit (the condition is checked at the start of the loop body) or bottom-exit (condition is checked at the end of the loop body). The significance of these subtypes is one of the major criteria in choosing the appropriate loop types when programming: In a top-exit loop, as the condition is checked at the start of the loop, there is always a possibility that the conditions stops the loop from executing even once i.e. in a top-exit loop, the loop may NEVER be executed 0 times. (note that the ForNext loop is also a top-exit loop) In a bottom-exit loop, regardless of the initial outcome of the condition, as it is checked at the end of the loop body, the loop body will always be executed at least once i.e. in a bottom-exit loop, the loop MUST be executed AT LEAST ONCE.
Page 5 of 17
Top-exit Do loops must follow one of the following syntaxes (there are two types): 1) Do While Loop Do While Condition = True Do Something Loop For example; Dim intCounter, intResult As Integer 'the onus for initialising loop counters is now on the programmer intCounter = 1 Do While intCounter <= 12 intResult = intCounter * 10 lstResult.Items.Add(intCounter & " x " & 10 & " = " & intResult) 'incrementing the counter is now the programmers responsibility intCounter = intCounter + 1 Loop
Page 6 of 17
Programming Worksheets
The graphic below illustrates the expected behaviour of the Do While Loop construct:
2) Do Until Loop. Do Until Condition = True Do Something Loop For example; Dim intCounter, intResult As Integer 'the onus for initialising loop counters is now on the programmer intCounter = 1 'note the subtle chane in the condition for UNTIL Do Until intCounter > 12 intResult = intCounter * 10 lstResult.Items.Add(intCounter & " x " & 10 & " = " & intResult) 'incrementing the counter is now the programmers responsibility intCounter = intCounter + 1 Loop
The graphic below illustrates the expected behaviour of the Do Until Loop construct:
Page 7 of 17
Programming Worksheets
B) Bottom exit Do loops - Do Loop While / Do Loop Until: Bottom-exit Do loops must follow one of the following syntaxes (there are two types): 3) Do Loop While Do Do Something Loop While Condition = True For example; Dim intCounter, intResult As Integer 'the onus for initialising loop counters is now on the programmer intCounter = 1 Do 'this code block will now execute at least once intResult = intCounter * 10 lstResult.Items.Add(intCounter & " x " & 10 & " = " & intResult) 'incrementing the counter is now the programmers responsibility intCounter = intCounter + 1 Loop While intCounter <= 12 The graphic below illustrates the expected behaviour of the Do Loop While construct:
Page 8 of 17
Programming Worksheets
4) Do Loop Until Do Do Something Loop While Condition = True For example; Dim intCounter, intResult As Integer 'the onus for initialising loop counters is now on the programmer intCounter = 1 Do 'this code block will now execute at least once intResult = intCounter * 10 lstResult.Items.Add(intCounter & " x " & 10 & " = " & intResult) 'incrementing the counter is now the programmers responsibility intCounter = intCounter + 1 Loop Until intCounter > 12
The graphic below illustrates the expected behaviour of the Do Loop Until construct:
Page 9 of 17
Programming Worksheets
Infinite Loops and DoEvents When programming loops the developer needs to extra careful with do loops as they are able to permanently lock a program in an infinite loop if the condition to exit the loop is never met. This means that the program will no longer appear to respond. Therefore a developer needs to make sure when programming a do loop that at some point the loop will exit from continuous execution. Very occasionally a do loop may actually need to (be intended) run for a long period of time. If this is a natural course for the loop, the user may well think that the program has crashed even if it is still working. It is at this point that the DoEvents method comes in useful. The DoEvents method basically forces the loop to release some of the processor time to perform other tasks. This ultimately means that the computer looks at any other actions that are attempting to be executed and intermittently allows them to happen. The Application.DoEvents() statement needs to be put inside the loop in which it is required: Do While Condition = True Application.DoEvents() Do Something Loop Note that sometimes the effect of the program being locked in an infinite loop is also useful - i.e. when you need to continually to monitor some condition while the program is running.
Page 10 of 17
Programming Worksheets
The example below illustrates the combined effect of a infinite loop and the DoEvents( ) method. The graphic below that shows the output of the code shown. Why is the loop considered an infinite loop? Why did the exception raise when the loop counter got to 3,277?
Page 11 of 17
On some occasions there is a need to exit a loop, conditional statement or even procedure (well look at these later) early. Exit statements can save a lot of extra processing for your program. Statements blocks that can be exited from include: For loops Do loops If Statements Case Statements Try Statements Procedures Exit For Exit Do Exit If Exit Select Exit Try (will discuss later) Exit Sub / Exit Function (will discuss later)
For example, the following code leaves the Do loop early when a condition other than the loops termination condition is met: Dim intCounter, intResult As Short intCounter = 1 Do 'this early exit will get rid of our 'infinite loop problem If intCounter >= 12 Then Exit Do End If intResult = intCounter * 10 lstResult.Items.Add(intCounter & " x " & 10 & " = " & intResult) intCounter = intCounter + 1 lblLoopIterations.Text = "No of Iterations = " & intCounter Loop While intCounter >= 1
Demonstration Using loops of all types Your tutor will demonstrate the use of the various types of loop constructs available in VB.NET. The demonstration will also include: an illustration of an infinite loop the use of DoEvents in long loops, and how to exit a loop early.
Page 12 of 17
Programming Worksheets
Page 13 of 17
Programming Worksheets
5. Add a Click Event Handler to the button entitled Calculate times table up to 12>> (remind yourself how to do this from previous labs). In the code stub that appears, add the following code: 'what do the following two lines of code do? Dim LoopCounter As Integer Dim CurrentValue As Integer = nmSelectNumber.Value lblTimesTable.Text = "Times table for: " & CurrentValue lblUpTo.Text = "Up To 12" 'what does the following line of code do? lbxTimesTableDisplay.Items.Clear() 'set up FOR...NEXT loop to calcuate times table from 1 to 12 For LoopCounter = __ To ___ 'create the formatted string to be displayed... DisplayString = CurrentValue & " Times " & LoopCounter & " = "& (CurrentValue * LoopCounter)) '... and display it lbxTimesTableDisplay.Items.Add(DisplayString) Next 6. Take some time to figure out how the code you have added works. The comments (green lines with an apostropphe () symbol at the start) should help. Use the following questions to test your understanding and explain it in your own words. 7. The code, as it stands, will not work, Why? Fix the error. 8. What do you think the first two lines of code (starting with Dim) do ?
10. Complete the line of code that starts the loop (starting with For) use the comment to guide you.
Page 14 of 17
Programming Worksheets
11. Now run the partially completed program (refer to previous labs on how to do this), does the first button perform as you expected? If not, note down what was different, and work out why.
12. Now add the second button Click event handler for the button entitled Change Limit and Calculate. 13. Before you write any code, what do you think the purpose of this button is?
14. For the new buttons click event handler, you will need to work out what code you need to add to achieve its desired behaviour. You must use any loop other than the For Next loop to achieve the functionality expected (as the limit is now a variable rather than pre-fixed at 12) Hint: Use the code already added for the btnCalculateTable buttons click event in step 5 to decide how you want the code behind the other button to behave (and look like). You will need to look at your lecture notes on loops and the. 15. Which loop construct did you chose in the last step? Why?
16. Remind yourself of the distinction between top-exit and bottom-exit loops (see lecture notes). If you chose a top-exit loop in the previous steps, try changing it to one of the bottom-exit loops (and vice-versa). Does the code behaviour change?
17. Remind yourself of the distinction between While type and Until type loops (see lecture notes). If you chose a While type loop in the previous steps, try changing it to one of the Until type loops (and vice-versa). Does the code behaviour change?
Page 15 of 17
Programming Worksheets
3. A typical iterative algorithm (that would lead to the output in step 3) for Factorials is: 'Declare a loopcounter as a whole number 'and a (whole number)variable to hold the chosen number 'Initialise a varialbe to hold the Factorial as 1 'Clear out display area (e.g. Listbox) 'Get selected (whole number) value from user (e.g. using a NumericUpDown) 'start a loop to iterate up to selected number ' update Factorial value b multiplying rpevious result by current loopcounter value ' create a formatted string to be displayed... '... and display it 'end of loop 'format string to display final message Factorial of x is y '... and display it Hint: To get you started, Create the form based on what you see in step 4, create the appropriate button click event handler, and add the comments above as a template for writing the actual code (Pseudo code)
Page 16 of 17
Programming Worksheets
Page 17 of 17