Reputation: 25
I need to output basic compound interest that will be displayed in a message box using for loop
The message box needs to show a left column titled "Years" and a right column showing "Amount".
My code only displays the messagebox 5 times whereas I need it to all be displayed in a list
Here is what I have so far:
private void button1_Click(object sender, EventArgs e)
{
decimal amount;
decimal principal = 1000;
double rate = 0.05;
string msg;
msg = "Years \t Amount";
msg += Environment.NewLine;
for (int year = 1; year <= 5; year++)
{
amount = principal * ((decimal)Math.Pow(1.0 + rate, year));
msg += amount.ToString("C");
msg += Environment.NewLine;
}
MessageBox.Show(msg, "Compund Interest");
Upvotes: 1
Views: 183
Reputation: 9389
private void button1_Click(object sender, EventArgs e)
{
decimal amount;
decimal principal = 1000;
double rate = 0.05;
string msg;
// start building string here i.e. msg = "header \t header" \t places a tab
// add a carriage return msg += Enviornment.Newline
for (int year = 1; year <= 5; year++)
{
amount = principal * ((decimal)Math.Pow(1.0 + rate, year));
// don't overwrite msg but append to it msg += "year number use your counter \t" += what you are already doing below.
msg = amount.ToString("C");
// then add your carriage return again.
}
MessageBox.Show(msg);
}
Upvotes: 0
Reputation: 1140
private void button1_Click(object sender, EventArgs e)
{
string amount = "";
decimal principal = 1000;
double rate = 0.05;
for (int year = 1; year <= 5; year++) {
amount += string.Format("{0:C}", principal * Convert.ToDecimal(Math.Pow(1.0 + rate, year))) + Environment.NewLine;
}
MessageBox.Show(amount, "Compound Inerest");
}
Upvotes: 1