Hot-Link Menu in Right-Side Column

Last Updated 6-30-2010


7.1 Why use Loops?

Repetition structures, known as loops, offer a flexible yet convenient way to repeatedly process instructions in a program. Loops have many applications in computer programming. For example, when one searches for a certain product on eBay or when searching Google, the program uses a loop to search through many records and finds those with matching or similar keywords. Loops are also used in computer graphics programming, such as animation. Many frames are displayed within a loop showing an animation. Loops are also used when programming microprocessors and computing numerical series.

7.2 Introduction

There are three basic programming structures that are used in high-level programming languages. These structures are sequential, selection, and repetition. The sequential structure is a segment of code where the statements get executed in a sequence from top to bottom. The selection structure involves an If or a Select/Case statement, where the program execution branches to a new line, based on the outcome of a decision. The repetition structure, often referred to as a Loop, is used when a segment of code needs to be executed repeatedly. Usually, a condition controls the continuation of a loop. There are different repetition structures available in Visual Basic VB.NET.

7.3 Terminology

There are certain terms that are used when working with loops. Here are some of the common terms that you should familiarize yourself with before reading any further:

  • Body of the loop: Body of the loop is the segment of code that gets executed repeatedly.
  • Iteration/Cycle: Each time the statements in the loop body get executed is referred to as one iteration or cycle.
  • Loop Condition: There is usually a condition that controls the continuation or termination of a loop. For example, a loop may continue as long as the temperature is above 60 degrees.
  • Loop Variable: There is usually one variable that is used in forming the loop condition. This variable is referred to as the loop variable. It is possible to have more than one variable in the loop condition.

7.4 Different Kinds of Loops

In general, there are two categories of loops: pretest loops and posttest loops.

Pretest Loops

In a pretest loop, the condition gets evaluated at the beginning of the loop cycle. Therefore, the body of the loop will not get executed if the condition does not hold the very first time.

Posttest Loop

In a posttest loop, the loop condition gets evaluated at the end of the loop cycle. Therefore, the body of the loop will get executed at least once, regardless of the condition. This is a major difference between a pretest loop and a posttest loop. You may choose a posttest loop if the problem description justifies the body of the loop be executed at least once.

Repetition Structures in Visual Basic VB.NET

  • For...Next (pretest loop)
  • Do-While...Loop (pretest loop)
  • Do-Until...Loop (pretest loop)
  • Do...Loop-While (posttest loop)
  • Do...Loop-Until (posttest loop)
  • Do...Loop (unconditional loop)

The first three loop structures are important. Any problem that requires repetition can be coded using one of these loops. The other loop structures are provided for your information and are not used as often.

Actually, there is one more repetition structure: For Each...Next, which can be used when processing array elements. This loop structure will not be discussed in this chapter. If you would like to learn more about the For Each...Next, refer to online resources.

7.5 For...Next Loop

The For loop is also known as a counting loop. It is an ideal loop structure when the number of iterations is known. It always contains a loop variable that works like a counter. The For loop is a powerful loop structure, in the sense that the initialization of the loop variable, to loop condition, and the updating of the loop variable are all embedded in the syntax of the loop. Below is the general syntax of the For loop.

General Syntax (keywords are in bold):

For LoopVariable = InitialValue To EndValue Step StepValue
   Body of the loop
Next LoopVariable

When a For loop begins, the LoopVariable gets initialized to the InitialValue. This initialization happens only once. The range of the values that the LoopVariable can assume is from the InitialValue to the EndValue.

Key Points to Remember

  • A For loop is also known as a counting loop.
  • A For loop is a pretest loop.
  • A For loop is the preferred choice when the number of iterations is known.
  • The LoopVariable gets updated by the StepValue upon execution of the last line in the loop (Next).
  • The StepValue can be a positive or a negative value.
  • Including the LoopVariable after Next is optional.
  • If there is no StepValue specified in the first line, the default StepValue =1 will be used.

EXAMPLE 1

Assignment: Write a For loop to display "Hail Purdue" ten times in a label.

This is an ideal problem to solve using a For loop, because it is a counting problem and the number of iterations is known. A computer program to solve this problem needs one variable that is used as a counter. The loop should iterate ten times, and each time "Hail Purdue" should be displayed in the label. The most natural way of counting ten times is from 1 to 10. Therefore, the loop variable may start with the initial value of 1 and go up to the end value of 10, with the step value of 1. Below is the pseudocode for this solution:

Pseudocode

  1. Declare a loop variable of type Integer.
  2. Start a For loop, with initial value of 1, end value of 10, and StepValue of 1.
    1. Display "Hail Purdue" in the Label.
    2. Next: loop variable gets updated.
    3. The loop continues, if the loop variable is within the range.

Create a Label changing the characteristics as indicated in the diagram below:

Solution to 7.1

  • BorderStyle==>Fixed3D
  • Font==>14 pt
  • Name==>lblShow
lbl.Show

Code

Public Class Form1

  Private Sub Form1_Load( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    Dim Count As Integer

    For Count =1 to 10 step 1
      lblShow .Text = lblShow .Text & "Hail Purdue" & vbCrLf
    Next

  End Sub
End Class

Form At Runtime

Form 7_1


Visual Basic VB.NET - EXAMPLE 2

Assignment: Write a For loop to add up all the numbers from 1 to 100, i.e. 1+2+3...+100.

This is also a good problem to solve using a For loop, because the number of iterations is known. To write a computer program for this problem, you need two variables: one variable to add up the numbers and a loop variable to assume the values 1, 2, ...100. Hence, the loop variable should start with the initial value of 1, and go up to the end value of 100, with the StepValue of 1. In the body of the loop, the loop variable should be added to the sum of the numbers. Let us look at the pseudocode followed by the program to solve this problem.

Pseudocode

  1. Declare two variables, one to add up the numbers, and a loop variable.
  2. Initialize the sum of numbers to 0.
  3. Start a For loop; LoopVariable starts with 1, ends with 100, and increments by 1.
    1. Add the loop variable to the sum of numbers.
    2. At the Next keyword, the variable is incremented by the StepValue of 1.
    3. The loop continues as long as the loop variable is less than or equal to 100.

Create a Label for output changing the characteristics as indicated in the diagram below. Change the Form Text to Sum 1 to 100 and double-click on the form to enter the text in the diagram below:

Solution to 7.2

Form at Design:

Form 7_2

Form at Runtime:

7_2 Running

lblShow Properties:

7_2 Properties
Public Class Form1
Private Sub Form1_Load( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    Dim Num As Integer
    Dim Sum As Integer

    For Num = 1 to 100
      Sum+=Num
    Next

    lblShow .Text = "Sum of Numbers= " & Sum .ToString

End Sub
End Class


For Loop with Negative Step Value

Sometimes the logic of the problem requires a For loop with negative step values. In such cases, the initial value must be greater than the end value for the loop to execute. In other words, the loop variable starts with the initial value and steps down to the end value.

For example, the following loop displays the numbers from 10 to 1 in a Label:

Dim Num as Integer
For Num=10 to 1 Step -1
    lblOutput &= Num.ToString & vbcrlf
Next

7.6 Do-While...Loop

The Do-While is a pretest loop. It is a good choice when the number of iterations is not known and the logic of the problem suggests that the loop should continue as long as a condition evaluates to TRUE. To understand the logic of the Do-While loop, let us consider something realistic. For example, the night before the exam, a student thinks "I will keep studying, while the library is open" or a person in a casino says "I will keep putting quarters in the slot machine, while I have quarters in my pocket." There is usually a loop variable that is used to from the condition of the loop. Unlike the For loop, the initialization and updating ofthe loop variable is not a part of the syntax. Below is the general syntax of the Do-While loop:

Do While condition
    Body of the loop
Loop


Visual Basic VB.NET - EXAMPLE 3

Assignment: Write a Do-While loop to add up all the numbers from 0 to 100, i.e. 0+1+2+3...+100.

Although this is an ideal problem to code using a For loop, you may, use a Do-While loop as well. As explained before, to write a computer program for this problem, you need two variables: one variable to add up the numbers and a loop variable to assume the values 0,1,2...100. The variables should be initialized to 0 before the loop. Although VB.Net initializes all the numeric values to 0, it is a good practice to explicitly initialize the variables and their initial values. the condition of the loop should be formed for the continuation of the loop. Therefor the condition should be while the loop variable is less than or equal to 100. In the body of the loop, the loop variable should be added to the sum of the numbers, and then incremented by 1 to assume the next value. Below is the pseudocode for this problem using a Do-While loop.

Pseudocode

  1. Declare two variables; a loop variable and a variable to add up the numbers.
  2. Initialize both variables to 0.
  3. Start a Do-While loop with the condition: LoopVariable<=100.
    1. Add the loop variable to the sum of the numbers.
    2. Increment the loop variable by 1.
    3. Back to step 3, loop continues if the condition evaluates to TRUE.
  4. After the loop, display the sum of numbers in the Label.

Create a Label for output changing the characteristics as indicated in the diagram below. Change the Form Text to Do-While Sum 0 to 100 and double-click on the form to enter the text in the diagram below:

Solution to 7.3

Form at Design:

Form 7_3

Form at Runtime:

7_3 Running

lblShow Properties

7_3 Properties
Public Class Form1

Private Sub Form1_Load( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim Sum As Integer
    Dim Num As Integer

    Do While Num <= 100
      Sum+=Num
      Num+=1
    Loop

    lblShow.Text = "Sum Total: " & Sum .ToString

End Sub
End Class


Home


Visual Basic

Introduction to VB.NET

.NET Framework

VS2008 IDE

How VB is Compiled

Start Visual Studio


Windows Form App


Save Your Work

VB OOP Programming

Visual Basic Code


Exit Code


Button Event Code

Coding Recommendations

If/Then/Else

Error List Window

Comment Syntax

Help Window

Language Essentianl

Built-In Data Types


Declare Variables

Declare Constants

Code Arithmetic Expressions

Assignment Statements

Operator Precedence

Type Casting


Math Class

String Declaration

Conversion Functions

Conversion Methods

Formatting Functions

String Formatting


Variable Scope

Enumerations

Nullable Types


Loop Constructs

For Next Loop

Do While Loop


Do Until Loop

Do...Loop-While

Do...Loop-Until


Exit Do | Exit For

Do...Loop


Nested Loops


Arrays

Array Declaration


Rnd( ) Function

Listbox Control


KeyPressEventArgs


Parallel Arrays

Key Event Args


Dynamic Arrays

Redimension Array

Set Breakpoint

Start Debugger


ReDim Preserve


MultiDimensional Arrays

DataGridView Control


Length and Sort Methods


Structures

Pad Right

Split Method

IsNumeric Function


Multiform Projects


Add Form To Project

Form Object Methods

Form Show Method

ShowDialog Method

Form Close Method

Form Accept Button

Multiform Project Example


ASP.NET Web Programming

Create Data Source


Configure Access Data Source


Add Product Class


Extract Local Database Data

Order PageLoad VB Code

Add New Web Page


Set Start Page

Display Cart Aspx Code

Display Cart Design View

Sorted List Definition

VB.NET Session State


Create CartItem Class

GetCartContents Function


Add To Cart Event Handler

Remove Cart Item Event


Clear Cart Event Handler