Repetition/Looping Statements

 

A loop is used to repeat a sequence of statements a number of times. At each repetition or pass, the statements act upon variables whose values are changing.

 

Do…Loops

 

A Do…Loop repeats a sequence of statements either as long as or until a certain condition is true. A Do statement precedes the sequence of statements, and a Loop statement follows the sequence of statements.

 

Use a Do…Loop to execute a block of statements an indefinite number of times. There are several variations of the Do...Loop statement, but each evaluates a numeric condition to determine whether to continue execution. As with If...Then, the condition must be a value or expression that evaluates to False (zero) or to True (nonzero).

 

Do While…Loop

 

Syntax:

 

Do While <condition>

    <statement/s>

Loop

 

When the loop is executed, VB first checks the truth value of condition. If condition is false, the statements inside the loop are not executed, and the program continues with the line after the Loop statement. If condition is true, the statements inside the loop are executed. When the Loop statement is encountered, the entire process is repeated, beginning with the testing of condition in the Do While statement.

 

Flowchart:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 Sample Code:

 

The following program displays the numbers from 1 through 10.

 

Private Sub cmdDisplay_Click()

      Dim num As Integer

 

      num = 1

      Do While num <= 10

            Print num;

            num = num + 1

      Loop

End Sub

 

Do…Loop Until

 

Syntax:

 

Do

    <statement/s>

Loop Until <condition>

 

When the loop is executed, VB first executes the statements inside the loop and then checks the truth value of condition. If condition is true, the program continues with the line after the Loop statement. If condition is false, the entire process is repeated, beginning with the Do statement.

 

Flowchart:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  

Sample Code:

 

Do…Loops can also be used to ensure that a proper response is received from the InputBox function. For example, the following code segment prompts a user to continue or exit the program.

 

 Private Sub cmdDisplay_Click()

      Dim ans As String

 

      Do

            ans = InputBox(“Do you want to continue[Yes/No]?”)

            ans = Ucase(ans)

            ‘code to calculate something

            ...

      Loop Until ans = “No”

End Sub

 

Sample Program

 

Suppose you deposit P100 into a savings account and let it accumulate at 7% interest compounded annually. The following program determines when you will be a millionaire.

 

Properties

 

Object

Property

Setting

frmInterest

Caption

7% Interest

lblAmount

Caption

Amount Deposited

txtAmount

Text

(blank)

cmdYears

Caption

Years to become a millionaire

lblWhen

BorderStyle

1 - Fixed Single

 

Caption

(blank)

 

Source Code

 

Private Sub cmdYears_Click()

     Dim balance As Single, numYears As Integer

     

           balance = Val(txtAmount.Text)

           numYears = 0

           Do While balance < 1000000

                  balance = balance + 0.07 * balance

                  numYears = numYears + 1

            Loop

            LblWhen.Caption = numYears

End Sub

 

Exercise

 

1.        Illustrate the growth of money in a savings account. When the user presses the command button, values for Amount and Interest Rate are obtained from textboxes and used to calculate the number of years until the money doubles and the number of years until the money reaches a million pesos. Note: The balance at the end of each year is (1 + r) times the previous balance, where r is the annual rate of interest in decimal form. Use Do…Loops to determine the number of years.

 

Properties

 

Object

Property

Setting

frmInterest

Caption

Compound Interest

lblAmount

Alignment

1 - Right Justify

 

Caption

Amount

txtAmount

Text

(blank)

lblRate

Alignment

1 - Right Justify

 

Caption

Interest Rate (Annual)

txtRate

Text

(blank)

cmdDetermine

Caption

Determine Years

lblDouble

Alignment

1 - Right Justify

 

Caption

Doubling Time (Years)

lblAnsDouble

BorderStyle

1 - Fixed Single

 

Caption

(blank)

LblMillion

Alignment

1 - Right Justify

 

Caption

Reach a Million (Years)

lblAnsMillion

BorderStyle

1 - Fixed Single

 

Caption

(blank)

  

2.        Write a program that represents the following flowchart that requests an integer greater than 1as input and factors it into a product of prime numbers.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

3.        Write a program that represents the following flowchart that finds the greatest common divisor (the largest integer that divides both) of 2 positive integers entered by the user.

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

For…Next Loops

 

Used when you know you must execute the statements a specific number of times. Unlike a Do…Loop, a For…Loop uses a variable called a counter that increases or decreases in value during each repetition of the loop.

 

Syntax

 

For <counter> = <start> To <end> [Step <increment>]

    <statement/s>

Next [<counter>]

 

The arguments counter, start, end, and increment are all numeric.

 

Note:  The increment argument can be either positive or negative. If increment is positive, start must be less than or equal to end or the statements in the loop will not execute. If increment is negative, start must be greater than or equal to end for the body of the loop to execute. If Step isn't set, then increment defaults to 1.

 

In executing the For loop, Visual Basic:

1.        Sets counter equal to start.

2.        Tests to see if counter is greater than end. If so, Visual Basic exits the loop. (If increment is negative, Visual Basic tests to see if counter is less than end.)

3.        Executes the statement/s.

4.        Increments counter by 1 or by increment, if it's specified.

5.        Repeats steps 2 through 4.

 

This code prints the names of all the available Screen fonts:

 
Private Sub Form_Click ()
   Dim I As Integer
   For i = 0 To Screen.FontCount
      Print Screen.Fonts(i)
   Next
End Sub

 

For Each...Next

 

A For Each...Next loop is similar to a For...Next loop, but it repeats a group of statements for each element in a collection of objects or in an array instead of repeating the statements a specified number of times. This is especially helpful if you don't know how many elements are in a collection.

 

Syntax:

 

For Each <element> In <group>

   <statement/s>

Next <element>

 

For example, the following Sub procedure opens Biblio.mdb and adds the name of each table to a list box.

 
Sub ListTableDefs()
   Dim objDb As Database
   Dim MyTableDef as TableDef
   Set objDb = OpenDatabase("c:\vb\biblio.mdb", _
   True, False)
   For Each MyTableDef In objDb.TableDefs()
      List1.AddItem MyTableDef.Name
   Next MyTableDef
End Sub

 

Keep the following restrictions in mind when using For Each...Next: