30.07.2013 Views

Visual Basic.NET How to Program (PDF)

Visual Basic.NET How to Program (PDF)

Visual Basic.NET How to Program (PDF)

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 5 Control Structures: Part 2 153<br />

19 ' calculate amount after each year<br />

20 For year = 1 To 10<br />

21 amount = principal * (1 + rate) ^ year<br />

22 output &= year & vbTab & _<br />

23 String.Format("{0:C}", amount) & vbCrLf<br />

24 Next<br />

25<br />

26 ' display output<br />

27 MessageBox.Show(output, "Compound Interest", _<br />

28 MessageBoxBut<strong>to</strong>ns.OK, MessageBoxIcon.Information)<br />

29<br />

30 End Sub ' Main<br />

31<br />

32 End Module ' modInterest<br />

Fig. Fig. 5.8 5.8 For/Next structure used <strong>to</strong> calculate compound interest (part 2 of 2).<br />

The For/Next structure executes its body 10 times, varying control variable year<br />

from 1 <strong>to</strong> 10 in increments of 1. Line 21 performs the calculation from the problem statement<br />

a = p (1 + r) n<br />

where a is amount, p is principal, r is rate and n is year.<br />

Lines 22–23 append additional text <strong>to</strong> the end of String output. The text includes<br />

the current year value, a tab character (vbTab) <strong>to</strong> position <strong>to</strong> the second column, the<br />

result of the method call String.Format("{0:C}", amount) and, finally, a newline<br />

character (vbCrLf) <strong>to</strong> start the next output on the next line. The first argument passed <strong>to</strong><br />

Format is the format string. We have seen Strings containing {0}, {1} and so on,<br />

where the digit within the braces indicates the argument being displayed. In Chapter 4, we<br />

used a more complicated format string <strong>to</strong> print a floating-point number with two digits after<br />

the decimal. In these more complicated format strings, such as "{0:C}", the first digit (0)<br />

serves the same purpose. The information specified after the colon (:) is called the formatting<br />

code. The C (for “currency”) formatting code indicates that its corresponding argument<br />

(amount) should be displayed in monetary format. Figure 5.9 shows several formatting<br />

codes; a complete list can be found in the MSDN documentation “Standard Numeric<br />

Format Strings.” All formatting codes are case insensitive. Note that format codes D and X<br />

can be used only with integer values.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!