Free Web Hosting by Netfirms
Web Hosting by Netfirms | Free Domain Names by Netfirms


.

Home to new Visual Basic .NET programmers

Repetition Structures

 

Home ] What is this site? ] myExercises ] myTutorials ] myExam ] myMicrosoft ] myNotes ] Study Advice ] myLinks ]


Search (my)Visual Basic .NET

(Tip: Scroll past sponsored links to see your search results for this website)


Complain to Volkswagen South Africa (VWSA)


New to myExercises:

 

Lynnwood Consultants Program
Computer Calculator Program
Funny Time Program
Creative Minds Login Program
Hatfield Pizza & Pasta Program
  Shutterbug Program

New to myNotes:

 

>>

TOE chart


Order this book today from

kalahari.net: click-click, ding-dong

 

Title: Microsoft Visual Basic 2005:

         RELOADED, Second Edition

Author:  Diane Zak

 

Click the image below to order your copy.

 

Up ] GUI Standards ] Access Files ] Accumulators, Counters & Averages ] Arrays ] Collections ] Constants & Enumerators ] Crystal Reports ] Data Types ] Flowchart Symbols ] Functions ] Keywords ] Methods ] Operators ] Repetition Structures ] Selection Structures ] Sub Procedures ] Toolbox Controls ] Variables ] Windows Forms ]


 

Introduction

Pretest (top-driven loops)

Posttest (bottom-driven loops)

Types of Repetition Structures

    For...Next

    Do...Loop

    For Each...Next

 


 

Introduction

 

The Repetition Structure simply means to repeat or to loop certain pieces of code.  Every loop requires an evaluation or else it will result in an endless loop; at some point the condition must test false in order to exit the loop. 

 

Back to Top

 

Pretest (top-driven loops)

 

The condition is tested before entering the loop.  The loop will never execute unless the condition tests true.  In your code, the condition will appear before the code for the loop.  Pretest loops are most commonly used.  Pretest loops follow the True path.

 

Back to Top

 

Posttest (bottom-driven loops)

 

The loop is always executed one time.  Then only will the condition be tested.  Should the condition test true, the loop will execute a second time and so on.  If the condition should test false, the loop will not execute for a second time.  Posttest loops are used fairly seldom as it needs a specific reason to be used.  Posstest loops follow the False path.

 

Back to Top

 

Types of Repetition Structures

 

    For...Next

 

Is a pre-test (top-driven) loop.  Is used when you want the code to execute a precise number of times, e.g. to use the loop as a counter to execute a certain piece of code 5 times and then exit.

 

Syntax

 

 For counter = startvalue To endvalue [Step stepvalue]

   [statements]

 Next counter

   
For Signals the start of the For...Next loop
counter Is a numeric variable that keeps track of how many times the loop executes; remember to declare the counter variable; it will have a starting value equal to the value of the startvalue.
= Assignment operator
startvalue Tells the loop where to begin and must be numerical
To  
endvalue Tells the loop where to stop and must be numerical
Step Is optional, but will add a default stepvalue of +1.  It tells the loop "how much" (stepvalue) to add/subtract from the counter each time the loop is executed
stepvalue Is optional, is a default value of +1. It is the "how much" to add/subtract from the counter 

Rules:  

To use a positive stepvalue, e.g. +5, your startvalue must be less than or equal to the endvalue - you count upwards, therefore when the counter reaches the same value as that of the endvalue, the loop will stop

To use a negative stepvalue, e.g. -2, the startvalue must be greater than or equal to the endvalue - subtraction means counting downwards, therefore when the counter reaches the same value as that of the endvalue, the loop will stop

statements What code you want to execute with each loop
Next Adds the stepvalue to the counter and returns the loop to the start to test the condition again
counter Is optional, but recommended as code will be easier to read next time you look at it

 

Tips

 

* The loop will execute one last time when the counter value is equal to the endvalue
* Integers or decimals can be used
* For...Next loops are represented by a hexagon in flowcharts
* Use the Exit For statement to exit the For...Next loop before it finishes - if someting goes wrong in your loop, this statement will terminate the loop which will prevent your program from crashing
* For...Next loops can be nested within one another

 

Examples

 

Get three city names using an inputbox and display each city name and the value of the counter in a messagebox.

 

Dim intCount As Integer, strCity As String

For intCount = 1 To 3

    strCity = InputBox("Enter the city:", "City Entry")

    MessageBox.Show(strCity & " is city number " & intCount, "City", MessageBoxButtons.OK, _

    MessageBoxIcon.Information

Next intCount

 

Let the loop repeat until sngNumber has a value of 1 and display the results in the Output window of Visual Basic.  The counter is shrunk from 2.5 to 1 in increments of -0.5

 

Dim sngNumber As Single

For sngNumber = 2.5 To 1 Step -0.5

    Debug.WriteLine(sngNumber)

Next sngNumber

 

Move a picturebox around on your screen.

 

Dim intX As Integer

For intX = 0 To 275 Step 5

    Me.FruitPictureBox.SetBounds(intX, 0, 0, 0, BoundsSpecified.X)

Next intX

 

Back to Top

 

    Do...Loop

 

Can be a pretest or posttest loop.  Contains the keywords While or Until.  Is used to repeat certain instructions while or until certain conditions are met.

 

Priming read is when you require user input before the loop starts and while the loop is running, you request user input again, usually you ask the same question in both cases.  The purpose of priming read is that it sets up or prepares a loop, since this information is used when testing the loop condition.  A priming read prevents an endless loop.  See the examples below to see the practical use of priming read.

 

Syntax

 

Pretest Do...Loop

  Do {While | Until} condition

  (statements)

Loop

 

  Do Signals the start of the loop
  While

While will execute code while a certain condition is true, e.g while I'm speaking you need to take notes.

  Until

Until will execute code until a certain condition becomes true, e.g you may not leave the classroom until the bell rings.

  condition

- It is the requirement that has to be met.  

- Can contain variables, e.g intValue, strName;

constants, e.g conState;

properties, e.g. object.BackColor;

functions, e.g InputBox and 

operators, e.g +, *, And, OrElse  

- The condition must result in a boolean value, meaning either True or False

  statements What code you want to execute with each loop
  Loop Signals the return to the top of the loop
     

 

Posttest Do...Loop

  Do 

  (statements)

Loop {While | Until} condition

 

  Do Signals the start of the loop
  statements What code you want to execute with each loop
  Loop Returns the loop to the start
  While

While will execute code while a certain condition is true, e.g while I'm speaking you need to take notes.

  Until

Until will execute code until a certain condition becomes true, e.g you may not leave the classroom until the bell rings.

  condition

- It is the requirement that has to be met.  

- Can contain variables, e.g intValue, strName;

constants, e.g conState;

properties, e.g. object.BackColor;

functions, e.g InputBox and 

operators, e.g +, *, And, OrElse  

- The condition must result in a boolean value, meaning either True or False Values of other data types may also be used as long as they have been converted to boolean.

     

 

Tips

 

* Pretest loops follow the True path, while posttest loops follow the False path
* Use the Exit Do statement to exit the Do...Loop before it finishes - if someting goes wrong in your loop, this statement will terminate the loop which will prevent your program from crashing (see example below)
* Is represented by the diamond symbol in flowcharts
* Pretest and posttest loops do not render the same results, because the posttest loop executes statements before testing the condition
* Do...Loops can be nested within one another

 

Examples

 

Comparing a pretest and posttest Do...Loop to see the difference in results:

 

In this pretest loop example intCount is tested to see whether it is smaller or equal to 5.  If True, the value of intCount is displayed in the output window and 1 is added to intCount before returning the loop to the top.

 

Dim intCount As Integer = 10    'declare counter

Do While intCount <= 5

    Debug.WriteLine(intCount)

    intCount = intCount + 1     'update counter

Loop

 

In this posttest loop example, the current value of intCount, which is 1, is displayed in the Output window.  Then 1 is added to intCount, which makes it's value 2, followed by the condition to test whether intCount is larger than 5, before returning to the top of the loop.

 

Dim intCount As Integer = 10    'declare counter

Do

    Debug.WriteLine(intCount)

    intCount = intCount + 1     'update counter

Loop Until intCount > 5

 

In the Output window the results will display quite different:

 

Pretest loop results Posttest loop results
null 10

 

The pretest loop did not display a result because the condition was first tested and it tested false.  The posttest loop displayed a result of 10 because it executed the statements first before testing the condition.

 

Example of using priming read in a Do...Loop:

 

Dim strSales As String

Dim intNumSales As Integer                      'declare counter

Dim sngSumSales As Single                       'declare accumulator

Dim sngAverageSales As Single                   'declare average 

 

strSales = InputBox("Enter a sales amount.  Click Cancel when finished.", "Sales Entry")                       'priming read - get user input before commencing loop as this prepares the loop

Do While strSales <> ""                          'the condition uses the priming read information to execute the loop

intNumSales = intNumSales + 1                    'update counter

sngSumSales = sngSumSales + Val(strSales)        'update accumulator

strSales = InputBox("Enter a sales amount.  Click Cancel when finished.", "Sales Entry")                      'get user info while loop is running in order to satisfy the 

                                       'condition - otherwise loop will become endless

Loop

sngAverageSales = sngSumSales / intNumSales      'calculate average 

Me.AvgLabel.Text = Format(sngAverageSales, "currency")

 

*See flowchart in Zak, pg 377  (If you want this flowchart, send us an e-mail)

 

Using Exit...Do in a Do...Loop:


In the following example, Number is assigned a value that could cause the loop to execute more than 2 ^ 31 times. The If statement checks for this and exits if it exists, preventing endless looping.


Dim Counter As Integer = 0
Dim Number As Integer = 8
Do Until Number = 10
    If Number <= 0 Then Exit Do    'prevent an endless loop 
    Number = Number - 1
    Counter = Counter + 1
Loop
MsgBox("The loop ran " & Counter & " times.") 'runs 8 times

 

Back to Top

 

    For Each...Next

 

Don't confuse with For...Next loop.

Used when you want the code to execute for each object in a collection.

 

Back to Top

 


All content on this site is free for private use only  |  Contributions are encouraged  |  Thank you to Netfirms for the free hosting  |  If copyright content is published here or links to certain content violates some right/law, contact the Webmaster to have it removed immediately.

 

Site launched: October 2005  |  Updated: July 20, 2006  |  Link exchange  |  Site map  |  Contact us