Question about program flow
I am working my way through this book and I am a bit confused about the flow of this sample program:
Code:
' Fig. 3.4: Interest.vb
' Calculating compound interest.
Imports System.Windows.Forms
Module modInterest
Sub Main()
Dim amount, principal As Decimal ' dollar amounts
Dim rate As Double ' interest rate
Dim year As Integer ' year counter
Dim output As String ' amount after each year
principal = 1000
rate = 0.05
output = "Year" & vbTab & "Amount on deposit" & vbCrLf
' calculate amount after each year
For year = 1 To 10
amount = principal * (1 + rate) ^ year
output &= year & vbTab & _
String.Format("{0:C}", amount) & vbCrLf
Next
' display output
MessageBox.Show(output, "Compound Interest", _
MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub ' Main
End Module ' modInterest
The code displays a message box with 10 years' interest, but I don't see why. Since the message box code appears after the loop is complete, it seems to me that it would only display the last value of output, not all 10. I am really new to visual programming, and I can't figure out why the display code is not inside the loop. My background is in C/C++ so I am having trouble figuring this out. Thanks for any help.
Re: Question about program flow
VB Code:
Imports System.Windows.Forms
Module modInterest
Sub Main()
Dim amount, principal As Decimal ' dollar amounts
Dim rate As Double ' interest rate
Dim year As Integer ' year counter
Dim output As String ' amount after each year
principal = 1000
rate = 0.05
output = "Year" & vbTab & "Amount on deposit" & vbCrLf
' calculate amount after each year
For year = 1 To 10
amount = principal * (1 + rate) ^ year
'this is because the values are being appended to this string here
'notice the &= operator instead of just plain =
'this adds the string on to it, instead of setting it to the value
'if you were to change this to = then it would give you your expected
'result.
output &= year & vbTab & _
String.Format("{0:C}", amount) & vbCrLf
Next
' display output
MessageBox.Show(output, "Compound Interest", _
MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub ' Main
End Module ' modInterest
If your a C/C++ developer you may be more at home with C# than VB.Net.
Re: Question about program flow
Quote:
Originally Posted by <ABX
If your a C/C++ developer you may be more at home with C# than VB.Net.
But I want to learn VB. :confused:
This is not a "help me pick a programming language" post. I had a question about VB program flow.
Re: Question about program flow
I just added that as I thought it might help you, did you not notice the Extra comments I added to your code?
Re: Question about program flow
Quote:
Originally Posted by <ABX
I just added that as I thought it might help you, did you not notice the Extra comments I added to your code?
Ah, now I see, thank you. It is printing the final value of output, it is just that output contains several vbCrLfs. Thank you, and sorry I didn't notice your comments.