Section 6.4. Examples Using the For...Next Statement


6.4. Examples Using the For...Next Statement

The following examples demonstrate different ways of varying the control variable in a For...Next statement. In each case, we write the appropriate For...Next header.

  1. Vary the control variable from 1 to 100 in increments of 1.

     For i = 1 To 100 or For i = 1 To 100 Step 1 

  2. Vary the control variable from 100 to 1 in increments of -1 (decrements of 1).

     For i = 100 To 1 Step -1 

  3. Vary the control variable from 7 to 77 in increments of 7.

     For i = 7 To 77 Step 7 

  4. Vary the control variable from 20 to 2 in increments of -2 (decrements of 2).

     For i = 20 To 2 Step -2 

  5. Vary the control variable over the sequence of the following values: 2, 5, 8, 11, 14, 17, 20.

     For i = 2 To 20 Step 3 

  6. Vary the control variable over the sequence of the following values: 99, 88, 77, 66, 55, 44, 33, 22, 11, 0.

     For i = 99 To 0 Step -11 

Application: Summing the Even Integers from 2 to 100

The next two examples demonstrate simple applications of the For...Next repetition statement. The program in Fig. 6.5 uses the For...Next statement to sum the even integers from 2 to 100. Remember that to use the MessageBox class you must add a reference to System.Windows.Forms.dll, as explained in Section 3.8.

Figure 6.5. For...Next statement used for summation.

  1  ' Fig. 6.5: Sum.vb  2  ' Using For...Next statement to demonstrate summation.  3  Imports System.Windows.Forms  4  5  Module Sum  6     Sub Main()  7        Dim sum As Integer = 0  8  9        ' add even numbers from 2 to 100        10        For number As Integer = 2 To 100 Step 2 11           sum += number                        12        Next                                    13 14        MessageBox.Show( "The sum is " & sum, _              15           "Sum even integers from 2 to 100" , _             16           MessageBoxButtons.OK, MessageBoxIcon.Information) 17     End Sub ' Main 18  End Module ' Sum 

Message Dialog Buttons and Icons

The version of method MessageBox.Show called in Fig. 6.5 (lines 1416) is different from the version discussed in earlier examples in that it takes four arguments instead of two. The dialog in Fig. 6.5 is labeled to emphasize the effects of the four arguments. The first two arguments are Strings displayed in the dialog and the dialog's title bar, respectively. The third argument indicates which button(s) to display, and the fourth argument indicates an icon that appears to the left of the message. The documentation provided with the IDE includes the complete listing of MessageBoxButtons and MessageBoxIcon constants. The message dialog icon options are described in Fig. 6.6; the message dialog button options are described in Fig. 6.7, including how to display multiple buttons. Note that there are multiple icon constants that display the same icon. Sometimes using a different constant name improves program readability. For instance, it may make more sense to use the constant MessageBoxIcon.Warning to indicate that a warning is being displayed, while the constant MessageBoxIcon.Exclamation would be used to indicate that an unexpected result occurred. Both constants display the same icon, but the names used in the code are clearer based on context.

Figure 6.6. Message dialog icon constants.

MessageBoxIcon constants

Icon

Description

MessageBoxIcon.Exclamation and MessageBoxIcon.Warning

Both constants display an icon containing an exclamation point. Typically used to caution the user against potential problems or display information that may be unexpected.

MessageBoxIcon.Information and MessageBoxIcon.Asterisk

Both constants display an icon conataining the letter "i." Typically used to display information about the state of the application.

MessageBoxIcon.Question

This constant displays an icon containing a question mark. Typically used to ask the user a question.

MessageBoxIcon.Error, MessageBoxIcon.Stop and MessageBoxIcon.Hand

These constants display an icon containing an in a red circle. Typically used to alert the user of errors or critical situations.

MessageBoxIcon.None

 

This constant causes no icon to be displayed.


Figure 6.7. Message dialog button constants.

MessageBoxButton constants

Description

MessageBoxButtons.OK

OK button. Allows the user to acknowledge a message. Included by default.

MessageBoxButtons.OKCancel

OK and Cancel buttons. Allow the user to either continue or cancel an operation.

MessageBoxButtons.YesNo

Yes and No buttons. Allow the user to respond to a question.

MessageBoxButtons.YesNoCancel

Yes, No and Cancel buttons. Allow the user to respond to a question or cancel an operation.

MessageBoxButtons.RetryCancel

Retry and Cancel buttons. Allow the user to retry or cancel an operation that has failed.

MessageBoxButtons.AbortRetryIgnore

Abort, Retry and Ignore buttons. When one of a series of operations has failed, these buttons allow the user to abort the entire sequence, retry the failed operation or ignore the a failed operation and continue.


Application: Compound Interest Calculations

The next example computes compound interest using the For...Next statement. Consider the following problem statement:

A person invests $1000.00 in a savings account that yields 5% interest. Assuming that all the interest is left on deposit, calculate and print the amount of money in the account at the end of each year over a period of 10 years. To determine these amounts, use the following formula:

a = p (1 + r)n

where

p is the original amount invested (i.e., the principal)

r is the annual interest rate (e.g., .05 stands for 5%)

n is the number of years

a is the amount on deposit at the end of the nth year.

This problem involves a loop that performs the indicated calculation for each of the 10 years that the money remains on deposit. The solution is shown in Fig. 6.8.

Figure 6.8. For...Next statement used to calculate compound interest.

  1  ' Fig. 6.8: Interest.vb  2  ' Calculating compound interest.  3  Imports System.Windows.Forms  4  5  Module Interest  6     Sub Main()  7        Dim amount As Decimal ' dollar amounts on deposit     8        Dim principal As Decimal = 1000.00 ' amount invested  9        Dim rate As Double = 0.05 ' interest rate 10 11        ' amount after each year 12        Dim output As String = "Year" & vbTab & "Amount on deposit" & vbCrLf 13 14        ' calculate amount after each year                                   15        For year As Integer = 1 To 10                                        16           amount = principal * (1 + rate) ^ year                            17           output &= _                                                       18              (year & vbTab & String.Format("{0:C}", amount) & vbCrLf)       19        Next                                                                 20 21        ' display output 22        MessageBox.Show(output, "Compound Interest", _ 23           MessageBoxButtons.OK, MessageBoxIcon.Information) 24     End Sub ' Main 25  End Module ' Interest 

Lines 78 declare two Decimal variables. Type Decimal is used for monetary calculations. Line 9 declares rate as type Double. Variable principal is initialized to 1000.00 and rate is initialized to 0.05, (i.e., 5%). Variable output (line 12) will be used to store the output that we will eventually display in a message dialog.

The For...Next statement (lines 1519) iterates 10 times, varying control variable year from 1 to 10 in increments of 1. Line 16 performs the calculation from the problem statement

a = p (1 + r)n

where a is the amount, p is the principal, r is the rate and n is the year.

Formatting Currency Output

Lines 1718 append additional text to the end of String output. The text includes the current year value, a tab character (vbTab) to position to the second column, the result of the method call String.Format("{0:C}", amount) and, finally, a line feed (vbCrLf) to start the next output on the next line. Method Format of class String takes a formatted string and the values to be formatted as arguments, and returns the resulting text with the formatting applied. The first argument passed to Format is the format string. In Chapter 5, we used the format string "{0:F}" to print a floating-point number with two digits after the decimal. Line 18 uses the format string "{0:C}". The C (for "currency") format specifier indicates that its corresponding value (amount) should be displayed in monetary formatwith a dollar sign to the left and commas in the proper locations. For example, the value 1334.50, when formatted using the C format specifier, will appear as "$1,334.50."

Type Decimal vs. Type Double

Variables amount and principal are declared as type Decimal. We do this because we are dealing with fractional parts of dollars and need a type that allows precise calculations with monetary amountsSingle and Double, because they only approximate values, do not. Using floating-point types, such as Single or Double, to represent dollar amounts (assuming that dollar amounts are displayed with two digits to the right of the decimal point) can cause errors. For example, two Double dollar amounts stored in the machine could be 14.234 (normally rounded to 14.23) and 18.673 (normally rounded to 18.67). When these amounts are added together, they produce the internal sum 32.907, which normally rounds to 32.91. Thus, the output could appear as

   14.23 + 18.67 _______   32.91 


but a person adding the individual numbers as displayed would expect the sum to be 32.90. Therefore, it is inappropriate to use Single or Double for dollar amounts. You have been warned!

Error-Prevention Tip 6.3

Do not use variables of type Single or Double to perform precise monetary calculations. The imprecision of floating-point numbers can cause errors that result in incorrect monetary values. Use the type Decimal for monetary calculations.


Variable rate, of type Double, is used in the calculation 1 + rate, which appears as the left operand of the exponentiation operator. In fact, this calculation produces the same result each time through the loop, so performing the calculation in the body of the For...Next loop is wasteful.

Performance Tip 6.1

Avoid placing inside a loop the calculation of an expression whose value does not change each time through the loop. Such an expression should be evaluated only once and prior to the loop.




Visual BasicR 2005 for Programmers. DeitelR Developer Series
Visual Basic 2005 for Programmers (2nd Edition)
ISBN: 013225140X
EAN: 2147483647
Year: 2004
Pages: 435

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