Section 6.3. For... Next Loops


[Page 277 (continued)]

6.3. For... Next Loops

When we know exactly how many times a loop should be executed, a special type of loop, called a For... Next loop, can be used. For... Next loops are easy to read and write, and have features that make them ideal for certain common tasks. The following code uses a For... Next loop to display a table:

Private Sub btnDisplayTable_Click(...) Handles btnDisplayTable.Click  'Display a table of the first 5 numbers and their squares   'Assume the font for lstTable is Courier New   Dim i As Integer   For i = 1 To 5     lstTable.Items.Add(i & "  " & i ^ 2)   Next End Sub


[Run, and click on btnDisplayTable. The following is displayed in the list box.]

1  1 2  4 3  9 4  16 5  25


The equivalent program written with a Do loop is as follows.

Private Sub btnDisplayTable_Click(...) Handles btnDisplayTable.Click   'Display a table of the first 5 numbers and their squares   Dim i As Integer   i = 1   Do While i <= 5     lstTable.Items.Add(i & "  " & i ^ 2)     i += 1    'Add 1 to i   Loop End Sub


In general, a portion of a program of the form


[Page 278]

constitutes a For... Next loop. The pair of statements For and Next cause the statements between them to be repeated a specified number of times. The For statement designates a numeric variable, called the control variable, that is initialized and then automatically changes after each execution of the loop. Also, the For statement gives the range of values this variable will assume. The Next statement increments the control variable. If m n, thenm, m + 1, ..., n in order, and the body is executed once for each of these values. If m > n, then the body is skipped and execution continues with the statement after the For... Next loop.


[Page 279]

When program execution reaches a For... Next loop, such as the one shown previously, the For statement assigns to the control variable i the initial value m and checks to see whether i is greater than the terminating value n. If so, then execution jumps to the line following the Next statement. If i<=n, the statements inside the loop are executed. Then, the Next statement increases the value of i by 1 and checks this new value to see if it exceeds n. If not, the entire process is repeated until the value of i exceeds n. When this happens, the program moves to the line following the loop. Figure 6.7 contains the pseudocode and flowchart of a For ... Next loop.

Figure 6.7. Pseudocode and flowchart of a For Next loop.
(This item is displayed on page 278 in the print version)


The control variable can be any numeric variable. The most common single-letter names are i, j, and k; however, if appropriate, the name should suggest the purpose of the control variable.

Example 1.

Suppose the population of a city is 300,000 in the year 2006 and is growing at the rate of 3 percent per year. The following program displays a table showing the population each year until 2010.

Object

Property

Setting

frmPopulation

Text

POPULATION GROWTH

btnDisplay lstTable

Text

Display Population


Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   'Display population from 2006 to 2010   Dim pop As Double = 300000, yr As Integer   Dim fmtStr As String = "{0,4}{1,12:N0}"   For yr = 2006 To 2010      lstTable.Items.Add(String.Format(fmtStr, yr, pop))      pop += 0.03 * pop   Next End Sub


[Run, and click the button.]


[Page 280]

The initial and terminating values can be literals, variables, or expressions. For instance, the For statement in the preceding program can be replaced by

Dim firstYr As Integer = 2006 Dim lastYr As Integer = 2010 For yr = firstYr To lastYr


In Example 1, the control variable was increased by 1 after each pass through the loop. A variation of the For statement allows any number to be used as the increment. The statement

For i = m To n Step s

instructs the Next statement to add s to the control variable instead of 1. The numbers m, n, and s do not have to be whole numbers. The number s is called the step value of the loop. Note: If the control variable will assume values that are not whole numbers, then the variable must be of type Double.

Example 2.
(This item is displayed on pages 280 - 281 in the print version)

The following program displays the values of the index of a For... Next loop for terminating and step values input by the user:

Object

Property

Setting

frmIndex

Text

For index = 0 To n Step s

lblN txtEnd

Text

n:

lblS txtStep

Text

s:

btnDisplay

Text

Display Values of Index

lstValues


Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   'Display values of index ranging from 0 to n Step s   Dim n, s, As Double   Dim index As Double   n = CDbl(txtEnd.Text)   s = CDbl(txtStep.Text)   lstValues.Items.Clear()   For index = 0 To n Step s     lstValues.Items.Add(index)   Next End Sub



[Page 281]

[Run, type 3.2 and .5 into the text boxes, and click the button.]

In the examples considered so far, the control variable was successively increased until it reached the terminating value. However, if a negative step value is used and the initial value is greater than the terminating value, then the control value is decreased until reaching the terminating value. In other words, the loop counts backward or downward.

Example 3.
(This item is displayed on pages 281 - 282 in the print version)

The following program accepts a word as input and displays it backwards:

Object

Property

Setting

FrmBackwards

Text

Write Backwards

lblWord

AutoSize Text

False Enter word:

txtWord btnReverse

Text

Reverse Letters

txtBackwards

ReadOnly

True


Private Sub btnReverse_Click(...) Handles btnReverse.Click   txtBackwards.Text = Reverse(txtWord.Text) End Sub Function Reverse(ByVal info As String) As String   Dim m, j As Integer, temp As String =""   m = info.Length   For j = m - 1 To 0 Step -1     temp &= info.Substring(j, 1)   Next   Return temp End Function



[Page 282]

[Run, type "SUEZ" into the text box, and click the button.]

Note: The initial and terminating values of a For ...Next loop can be expressions. For instance, the third and fourth lines of the function in Example 3 can be consolidated to

For j = info.Length - 1 To 0 Step -1


Declaration of Control Variables

The control variable of a For ... Next loop can be declared directly in the For statement. A statement of the form

For i As DataType = m to n


(possibly with a Step clause) both declares the control variable i and specifies its initial and terminating values. In this case, however, the scope of the control variable i is limited to the body of the For ... Next loop. For instance, in Example 1, the two statements

Dim yr As Integer For yr = 2006 to 2010


can be replaced by the single statement

For yr As Integer = 2006 to 2010


In Example 2, the two statements

Dim index as Double For index = 0 to n Step s


can be replaced by the single statement

For index As Double = 0 to n Step s


This feature is new to Visual Basic 2005 and is the preferred way to declare control variables of For... Next loops.

Nested For... Next Loops

The body of a For... Next loop can contain any sequence of Visual Basic statements. In particular, it can contain another For... Next loop. However, the second loop must be completely contained inside the first loop and must have a different control variable. Such a configuration is called nested For...Next loops. Figure 6.8 shows several examples of valid nested loops.


[Page 283]

Figure 6.8. Nested For Next loops.


Example 4.
(This item is displayed on pages 283 - 284 in the print version)

The following program displays a multiplication table for the integers from 1 to 3. Here j denotes the left factors of the products, and k denotes the right factors. Each factor takes on a value from 1 to 3. The values are assigned to j in the outer loop and to k in the inner loop. Initially, j is assigned the value 1, and then the inner loop is traversed three times to produce the first row of products. At the end of these three passes, the value of j will still be 1, and the value of k will have been incremented to 4. The first execution of the outer loop is then complete. Following this, the statement Next increments the value of j to 2. The statement beginning "For k" is then executed. It resets the value of k to 1. The second row of products is displayed during the next three executions of the inner loop and so on.

Object

Property

Setting

frmTable

Text

Multiplication Table

btnDisplay

Text

Display Table

lstTable

Font

Courier New


Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim row, entry As String   lstTable.Items.Clear()   For j As Integer = 1 To3     row = "" 
[Page 284]
For k As Integer = 1 To3 entry = j & " x " & k & " = " & (j * k) row &= entry & " " Next lstTable.Items.Add(row) Next End Sub


[Run, and press the button.]

Comments

  1. For and Next statements must be paired. If one is missing, the automatic syntax checker will complain with a wavy underline and a message such as "A 'For' must be paired with a 'Next'."

  2. Consider a loop beginning with For i = m To n Step s. The loop will be executed exactly once if m equals n no matter what value s has. The loop will not be executed at all if m is greater than n and s is positive, or if m is less than n and s is negative.

  3. The value of the control variable should not be altered within the body of the loop; doing so might cause the loop to repeat indefinitely or have an unpredictable number of repetitions.

  4. Noninteger step values can lead to roundoff errors with the result that the loop is not executed the intended number of times. For instance, a loop beginning with For i As Double = 1 To 2 Step .1 will be executed only 10 times instead of the intended 11 times. It should be replaced with For i As Double = 1 To 2.01 Step .1.

  5. Visual Basic provides a way to skip an iteration in a For ... Next loop. When the statement Continue For is encountered in the body of the loop, execution immediately jumps to the Next statement. An analogous statement Continue Do is available for Do loops. This feature is new in Visual Basic 2005.

  6. Visual Basic provides a way to back out of a For ... Next loop. When the statement Exit For is encountered in the body of the loop, execution jumps immediately to the statement following the Next statement. An analogous statement Exit Do is available for Do loops.


[Page 285]
Practice Problems 6.3

1.

Why won't the following lines of code work as intended?

For i As Integer = 15 To 1   lstBox.Items.AddItem(i) Next


2.

When is a For... Next loop more appropriate than a Do loop?

Exercises 6.3

In Exercises 1 through 12, determine the output displayed in the list box when the button is clicked.

1.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   For i As Integer = 1 To 4     lstBox.Items.Add("Pass #"& i)   Next End Sub


2.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   For i As Integer = 3 To 6     lstBox.Items.Add(2 * i)   Next End Sub


3.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   For j As Integer = 2 To 8 Step 2     lstBox.Items.Add(j)   Next   lstBox.Items.Add("Who do we appreciate?") End Sub


4.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   For countdown As Integer = 10 To 1 Step -1     lstBox.Items.Add(countdown)   Next   lstBox.Items.Add("blastoff") End Sub 


5.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim num As Integer   num = 5   For i As Integer = num To (2 * num - 3)     lstBox.Items.Add(i)   Next End Sub



[Page 286]
6.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   For i As Double = 3 To 5 Step .25     lstBox.Items.Add(i)   Next   lstBox.Items.Add(i) End Sub


7.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   'First entry in text file is number of records in file   Dim recCount As Integer   Dim name, mileTime As String   Dim sr As IO.StreamReader = IO.File.OpenText("MILER.TXT")   recCount = CInt(sr.Readline)   For miler As Integer = 1 To recCount     name = sr.Readline     mileTime = sr.Readline     lstBox.Items.Add(name & "  "& mileTime)   Next   sr.Close() End Sub


(Assume that the seven lines of the file MILER.TXT contain the following entries: 3, Steve Cram, 3:46.31, Steve Scott, 3:51.6, Mary Slaney, 4:20.5.)

8.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   'First entry in text file is number of records in file   Dim recCount, total, score As Integer   Dim sr As IO.StreamReader = IO.File.OpenText("SCORES.TXT")   recCount = CInt(sr.Readline)   For i As Integer = 1 To recCount     score = CInt(sr.Readline)     total += score 'Add the value of score to the value of total   Next   sr.Close()   lstBox.Items.Add("Average = "& total / recCount) End Sub


(Assume the file SCORES.TXT contains the entries 4, 89, 85, 88, 98.)

9.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim row, entry As String   For i As Integer = 0 To 2     row = ""     For j As Integer = 0 To 3       entry = CStr(i + (3 * j) + 1)       row &= entry & "    "     Next     lstBox.Items.Add(row)   Next End Sub



[Page 287]
10.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim row As String   For i As Integer = 1 To 5     row = ""     For j As Integer = 1 To i       row &= "*"     Next     lstBox.Items.Add(row)   Next End Sub


11.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim word As String   Dim num1, num2 As Integer   word = InputBox("Please enter a word.")   num1 = CInt(Int((20 - word.Length) / 2))   num2 = 20 - num1 - word.Length   lstBox.Items.Add(Asterisks(num1) & word & Asterisks(num2)) End Sub Function Asterisks(ByVal num As Integer) As String   Dim chain As String = ""   For i As Integer = 1 To num     chain &= "*"   Next   Return chain End Function


(Assume that the response is Hooray.)

12.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   'Display an array of letters   Dim info As String, letter As String   info = "DATA"   For i As Integer = 1 To info.Length     letter = info.Substring(i - 1, 1)     lstBox.Items.Add(RepeatFive(letter))   Next End Sub Function RepeatFive(ByVal letter As String) As String   Dim chain As String = ""   For i As Integer = 1 To 5     chain &= letter   Next   Return chain End Function



[Page 288]

In Exercises 13 through 16, identify the errors.

13.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   For j As Double = 1 To 25.5 Step -1     lstBox.Items.Add(j)   Next End Sub


14.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   For i As Integer = 1 To 3     lstBox.Items.Add(i & " "& 2 ^ i) End Sub


15.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   'Display all numbers from 0 through 20 except for 13   For i As Double = 20 To 0     If i = 13 Then       i = 12     End If     lstBox.Items.Add(i)   Next End Sub


16.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   For j As Integer = 1 To 4 Step 0.5     lstBox.Items.Add(j)   Next End Sub


In Exercises 17 and 18, rewrite the program using a For ... Next loop.

17.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   Dim num As Integer = 1   Do While num <= 9     lstBox.Items.Add(num)     num += 2    'Add 2 to value of num   Loop End Sub


18.

Private Sub btnDisplay_Click(...) Handles btnDisplay.Click   lstBox.Items.Add("hello")   lstBox.Items.Add("hello")   lstBox.Items.Add("hello")   lstBox.Items.Add("hello") End Sub


In Exercises 19 through 38, write a program to complete the stated task.

19.

Display a row of 10 stars (asterisks).

20.

Request a number from 1 to 20 and display a row of that many stars (asterisks).

21.

Display a 10-by-10 array of stars.


[Page 289]
22.

Request a number and call a Sub procedure to display a square having that number of stars on each side.

23.

Find the sum 1 + 1/2 + 1/3 + 1/4 + ... + 1/100

24.

Find the sum of the odd numbers from 1 through 99.

25.

You are offered two salary options for ten days of work. Option 1: $100 per day. Option 2: $1 the first day, $2 the second day, $4 the third day, and so on, with the amount doubling each day. Write a program to determine which option pays better.

26.

When $1000 is deposited at 5 percent simple interest, the amount grows by $50 each year. When money is invested at 5 percent compound interest, then the amount at the end of each year is 1.05 times the amount at the beginning of that year. Write a program to display the amounts for 10 years for a $1000 deposit at 5 percent simple and compound interest. The first few lines displayed in the list box should appear as in Figure 6.9.

Figure 6.9. Growth of $1000 at simple and compound interest.

Amount

Amount

Year

Simple Interest

Compound Interest

1

$1,050.00

$1,050.00

2

$1,100.00

$1,102.50

3

$1,150.00

$1,157.63


27.

According to researchers at Stanford Medical School (as cited in Medical Self Care), the ideal weight for a woman is found by multiplying her height in inches by 3.5 and subtracting 108. The ideal weight for a man is found by multiplying his height in inches by 4 and subtracting 128. Request a lower and upper bound for heights and then produce a table giving the ideal weights for women and men in that height range. For example, when a lower bound of 62 and an upper bound of 65 are specified, Figure 6.10 shows the output displayed in the list box.

Figure 6.10. Output for Exercise 27.

Height

Wt-Women

Wt-Men

62

109

120

63

112.5

124

64

116

128

65

119.5

132


28.

Table 6.3 (on the next page) gives data (in millions) on personal computer sales and revenues. Read the data from the file PC.TXT, and generate an extended table with two additional columns, Pct Foreign (percent of personal computers sold outside the United States) and Avg Rev (average revenue per computer sold in the United States).

29.

Request a sentence, and display the number of sibilants (that is, letters S or Z) in the sentence. The counting should be carried out by a function.

30.

Request a number, n, from 1 to 30 and one of the letters S or P. Then, depending upon whether S or P was selected, calculate the sum(s) or product(s) of the numbers from 1 to n. The calculations should be carried out in Function procedures.


[Page 290]

Table 6.3. Personal computer sales and revenues (in millions).

Year

U.S. Sales

Worldwide Sales

U.S. Revenues

1998

34.6

98.4

74,920

1999

40.1

116.2

80,200

2000

46.0

128.5

88,110

2001

43.5

132.0

77,000


31.

Suppose $800 is deposited into a savings account earning 4 percent interest compounded annually, and $100 is added to the account at the end of each year. Calculate the amount of money in the account at the end of 10 years. (Determine a formula for computing the balance at the end of one year based on the balance at the beginning of the year. Then write a program that starts with a balance of $800 and makes 10 passes through a loop containing the formula to produce the final answer.)

32.

A TV set is purchased with a loan of $563 to be paid off with five monthly payments of $116. The interest rate is 1 percent per month. Display a table giving the balance on the loan at the end of each month.

33.

Radioactive Decay. Cobalt 60, a radioactive form of cobalt used in cancer therapy, decays or dissipates over a period of time. Each year, 12 percent of the amount present at the beginning of the year will have decayed. If a container of cobalt 60 initially contains 10 grams, determine the amount remaining after five years.

34.

Supply and Demand. This year's level of production and price (per bushel) for most agricultural products greatly affects the level of production and price next year. Suppose the current crop of soybeans in a certain country is 80 million bushels and experience has shown that for each year,

[price this year] = 20 - .1 * [quantity this year]

[quantity next year] = 5 * [price this year] - 10,

where quantity is measured in units of millions of bushels. Generate a table to show the quantity and price for each of the next 12 years.

35.

Request a number greater than 3, and display a hollow rectangle similar to the one in Figure 6.11(a) with each outer row and column having that many stars. Use a fixed-width font such as Courier New so that the spaces and asterisks will have the same width.

Figure 6.11. Outputs for Exercises 35 and 36.


36.

Request an odd number, and display a triangle similar to the one in Figure 6.11(b)with the input number of stars in the top row.


[Page 291]
37.

A man pays $1 to get into a gambling casino. He loses half of his money there and then has to pay $1 to leave. He goes to a second casino, pays another $1 to get in, loses half of his money again, and pays another $1 to leave. Then, he goes to a third casino, pays another $1 to get in, loses half of his money again, and pays another $1 to get out. After this, he's broke. Write a program to determine the amount of money he began with by testing $5, then $6, and so on.

38.

Create the histogram in Figure 6.12. A file should hold the years and values. The first line in the file could be used to hold the title for the histogram.

Figure 6.12. Histogram for Exercise 38.


39.

Write a program to estimate how much a young worker will make before retiring at age 65. Request the worker's name, age, and starting salary as input. Assume the worker receives a 5 percent raise each year. For example, if the user enters Helen, 25, and 20000, then the text box should display the following:

Helen will earn about $2,415,995


40.

Write a program that accepts a word as input and determines if its letters are in alphabetical order. (Test the program with the words "almost," "imply," and "biopsy.")

Solutions to Practice Problems 6.3

1.

The loop will never be entered because 15 is greater than 1. The intended first line might have been

For i = 15 To 1 Step -1


or

For i = 1 To 15


2.

If the exact number of times the loop will be executed is known before entering the loop, then a For... Next loop should be used. Otherwise, a Do loop is more appropriate.




An Introduction to Programming Using Visual Basic 2005
Introduction to Programming Using Visual Basic 2005, An (6th Edition)
ISBN: 0130306541
EAN: 2147483647
Year: 2006
Pages: 164

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net