# Visual Basic 2012 Lesson 11- Looping

#### [Lesson 10] << [CONTENTS] >> [Lesson 12]

Looping is required when we need to process something repetitively until a certain condition is met. For example, we can design a program that adds a series of numbers until the sum exceeds a certain value. We can also write a program that prompts the user to enter data repeatedly until he or she enters the word ‘Finish’. In Visual Basic 2012, there are three types of Loops, they are the For…..Next loop, the Do loop. and the While…..End while loop

### 11.1 Looping using the For….Next Loop

The syntax is:

```For counter=startNumber to endNumber (Step increment)

One or more VB statements

Next
```

To exit a For…..Next Loop, you can place the Exit For statement within the loop, please refer to example 11.1 d.

#### Example 11.1 a

```Dim counter as Integer
For counter=1 to 10
Next
```

* The program will enter number 1 to 10 into the list box.

#### Example 11.1b

```Dim counter , sum As Integer
For counter=1 to 100 step 10
sum+=counter
Next
```

* The program will calculate the sum of the numbers as follows:

sum=0+10+20+30+40+……

#### Example 11.1c

```Dim counter, sum As Integer
sum = 1000
For counter = 100 To 5 Step -5
sum - = counter
Next
```

*Notice that increment can be negative.

The program will compute the
subtraction as follow:
1000-100-95-90-……….

#### Example 11.1d

```Dim n as Integer
For n=1 to 10
If n>6 then
Exit For
End If
Else
Next

```

The process will stop when n is greater than 6.

### 11.2 The Do Loop

The Do Loop structures are

a)

```Do While condition
Block of one or more statements
Loop
```

b)

```Do
Block of one or more statements
Loop While condition
```

c)

```Do Until condition
Block of one or more statements
Loop
```

d)

```Do
Block of one or more statements
Loop Until condition
```

* Exiting the Loop

Sometimes we need to exit a loop prematurely because of a certain
condition is fulfilled. The syntax to use is known as Exit Do. Let’s examine the following examples

#### Example 11.2(a)

`Do while counter`

* The above example will keep on adding until counter >1000.

The above example can be rewritten as

```Do
TextBox1.Text=counter
counter+=1
Loop until counter>1000
```

#### Example 11.2(b)

```Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim sum, n As Integer