Ok. So I'm trying to have a program.. where the user enters his salary and then the program will calculate his salary for the next four years with a raise of 2.5% each year.
I feel like I have done this completely wrong, because my loop is only calculating one time.. its not even showing four salary's.. not to mention having them each raised 2.5% each time.
private void btnDisplay_Click(object sender, EventArgs e)
{
int count;
for (count = 1; count <= 4; count++)
{
decimal Raise;
decimal Salary;
decimal Sum;
decimal Total;
Raise = Convert.ToDecimal(0.025);
Salary = Convert.ToDecimal(txtSalary.Text);
Sum = Salary * Raise;
Total = Salary + Sum;
label2.Text = Total.ToString("c");
}
txtSalary is whatever the user entered salary is.
label2 is the display of the calculation.
---------------- UPDATE: I have updated the code with the final product. Thanks to everyone for helping out especially Patrick Hofman! You are the best.. I couldn't have done it without you. ------------------------
private void btnDisplay_Click(object sender, EventArgs e)
{
decimal salary = Convert.ToDecimal(txtSalary.Text);
decimal raise = 0.025m;
decimal previous = salary;
for (decimal year = 1; year <= 4; year++)
{
decimal sum = previous * (1 + raise);
previous = sum;
listBox1.Items.Add(sum.ToString("c"));
}
I think you should have something like this:
private void btnDisplay_Click(object sender, EventArgs e)
{
decimal salary = Convert.ToDecimal(txtSalary.Text);
decimal raise = 0.025m;
decimal total = 0;
decimal previous = salary;
listBox1.Items.Add("Start: {0:N2}", salary);
for (int year = 1; year <= 4; year++)
{
decimal sum = previous * (1 + raise);
previous = sum;
total += sum;
listBox1.Items.Add("Year {0}: {1:N2}", year, sum);
}
listBox1.Items.Add("Total: {0:N2}", total);
}
Note I made some changes to the variables. Some were moved to keep them over the for loop.
The steps:
Start with setting the start point (previous) to the salary.
For each year, multiply the previous year's salary with the raise percentage +1.
Set the previous and add that year's salary to the total.
Show the total in the label.
int count;
Salary = Convert.ToDecimal(txtSalary.Text);
for (count = 1; count <= 4; count++)
{
Salary *= 1.025m;
}
label2.Text = Salary.ToString("c");
You need to make sure you're retrieve the salary once at teh beginning and don't overwrite it till the end.
Problem 1: You are declaring the variables inside the forloop.so each time they are initialised with their default values.
Solution 1: inorder to retain their last assigned values you need to move the declaration of the variables outside the loop.
Problem 2: you are not able to see the results/changes as you are updating the label inside the for loop without any delay.so evatually you can only see the last calculated result.
Solution2: You need to either create 4 different labels to show the 4 different results or you need to wait for some time for updating the label results in each iteration by using timer functionality.
Try This: using LabelArray
Label[] lblSalaries = new Label[4];
private void CreateControls()
{
int x = 0, y = 10;
for (int i = 0; i < lblSalaries.Length;i++ )
{
lblSalaries[i] = new Label();
x += 60;
lblSalaries[i].Size = new System.Drawing.Size(50, 30);
lblSalaries[i].Location = new System.Drawing.Point(x,y);
Controls.Add(lblSalaries[i]);
}
}
private void btnDisplay_Click(object sender, EventArgs e)
{
int count;
decimal Raise;
decimal Salary;
decimal Sum;
decimal Total;
CreateControls();
for (count = 1; count <= 4; count++)
{
Raise = Convert.ToDecimal(0.025);
Salary = Convert.ToDecimal(txtSalary.Text);
Sum = Salary * Raise;
Total = Salary + Sum;
lblSalaries[count-1].Text = Total.ToString("c");
}
}
Related
I have an assignment where I need to calculate the amount of money for 2 people where we have 2 different interest rates. I need to display the amount of money that they would have at each of the given age. The issue is that it only prints the final amount which is 60 years old, how do I print the correct amount at the correct age? Here is the code
Console.WriteLine("*************************Investing vs.Savings ************************* \n");
Console.WriteLine("{0,-25} {1,-30} {2,-30}","Age", "Linda's Account", "John's Account");
Console.Write("-----------------------------------------------------------------------\n");
for(int age=20;age<=60;age+=10)
{
double Linda = 1000;
double John = 1000;
for (int year=1;year<=40;year++)
{
double retLin = 0.06;
double retJon = 0.015;
Linda += Linda * retLin;
John += John * retJon;
}
Console.WriteLine("{0,-25}{1,-30:0.00} {2,-35:0.00}", age, Linda, John);
}
Console.Read();
If I figured it right, your desired response is a line of output for each person's balance on each deacde. To do this you only need one iteration in wich balances are increased based on each person's interest rate.
But to calculate the interest rate correctly, it should be added to the balance on every year. So a fixed inner loop of 10 iterations is needed for each decade.
The code is:
double Linda = 1000;
double John = 1000;
double retLin = 0.06;
double retJon = 0.015;
for (int age = 30; age <= 60; age += 10)
{
for (int i = 0; i < 10; i++)
{
Linda += Linda * retLin;
John += John * retJon;
}
Console.WriteLine("{0,-25}{1,-30:0.00} {2,-35:0.00}", age, Linda, John);
}
Note that this will not print tha balance on the starting decade (you can simply print the starting values before the loop operations).
I think this is what you need (comments in code):
Console.WriteLine("*************************Investing vs.Savings ************************* \n");
Console.WriteLine("{0,-25} {1,-30} {2,-30}", "Age", "Linda's Account", "John's Account");
Console.Write("-----------------------------------------------------------------------\n");
// It always is good idea to store info in variables, to give
// them meaning and easily parametrize the code.
var baseAge = 20;
var ageStep = 10;
var finalAge = 60;
// Of course, it would not make sense if you'd have just simple loop
// i = 0, i < limit, i++.
for (int age = baseAge; age <= finalAge; age += ageStep)
{
double Linda = 1000;
double John = 1000;
// Here you missed starting point, as it always calculated
// as if we were in first loop - we need account for that.
for (int year = age; year <= 40; year++)
{
double retLin = 0.06;
double retJon = 0.015;
Linda += Linda * retLin;
John += John * retJon;
}
Console.WriteLine("{0,-25}{1,-30:0.00} {2,-35:0.00}", age, Linda, John);
}
Console.Read();
Screenshot
Hi. I need help from you guy. How do I calculate or sum all the value into the last textbox. I put number in my picture just want to explain what I need here.
I put some amount to calculate GST and show it to Total Legal Fees textbox.
After number 1, I put temporarily amount just to put more than 1, so if I have other amount, I just click ADD button.
This Add button help me to show total amount from number 2. Example, if I got one fee $20 and other is fee is $30. So total is %50 and it show into Total Disbursement textbox.
This is the problem I got. How do I calculate all the Legal Fees Total and Disbursement Total and show it automatically on my Grand Total textbox?
Here my code for Add button.
private void btnAdd_Click(object sender, EventArgs e)
{
dgvDisList.ColumnCount = 2;
dgvDisList.Columns[0].HeaderText = "Category";
dgvDisList.Columns[1].HeaderText = "Amount";
string[] row = new string[] { cbDisCategory.Text, tbAmount.Text };
dgvDisList.Rows.Add(row);
// Sum Total dari GridView
int sum = 0;
for (int i = 0; i < dgvDisList.Rows.Count; ++i)
{
sum += Convert.ToInt32(dgvDisList.Rows[i].Cells[1].Value);
}
tbTotalDisbursement.Text = sum.ToString();
}
And here is my GST calculation
private void tbLegalFees_TextChanged(object sender, EventArgs e)
{
if (System.Text.RegularExpressions.Regex.IsMatch(tbLegalFees.Text, "^(\\$??)(\\d+)(\\.??)(\\d*)"))
{
decimal exGST = tbLegalFees.Text.StartsWith("") ? decimal.Parse(tbLegalFees.Text) : decimal.Parse(tbLegalFees.Text);
decimal incGST = exGST * (decimal)0.6;
decimal GST = incGST + exGST;
tbLegalFees.Text = string.Format("{0:f2}", exGST);
tbGSTpercent.Text = string.Format("{0:f2}", incGST);
tbTotalLegalFees.Text = string.Format("{0:f2}", GST);
}
}
I am trying to calculate the total price of items after adding them to a combo box from a list box. In the list box I have both the type of item and ts price. I want to see the total price to increase as I add each item (click addButton) to the combo box. But what i am seeing is that the item is added to the combo box but I see only individual item prices instead of the sum of the prices. Here is a sample of my code.
private void addButton_Click(object sender, EventArgs e)
{
decimal price; // variables to holds the price
decimal total = 0; // variables to hold the total
int counter;
for (counter=0; counter <= 5; counter++)
{
price = decimal.Parse(priceLabel2.Text);
// add items price
total += price;
// display the total amount
costLabel.Text = total.ToString("c");
}
Any help would be appreciated,
Change:
private void addButton_Click(object sender, EventArgs e)
{
decimal price; // variables to holds the price
decimal total = 0; // variables to hold the total
int counter;
for (counter=0; counter <= 5; counter++)
{
price = decimal.Parse(priceLabel2.Text);
// add items price
total += price;
// display the total amount
costLabel.Text = total.ToString("c");
}
to:
decimal total = 0; // variables to hold the total
private void addButton_Click(object sender, EventArgs e)
{
decimal price; // variables to holds the price
int counter;
for (counter = 0; counter <= 5; counter++)
{
price = decimal.Parse(priceLabel2.Text);
// add items price
total += price;
// display the total amount
costLabel.Text = total.ToString("c");
}
}
The important change here is moving the total variable outside the function. This means that the value is maintained between clicks. If you put it inside the function it is reset to 0 on every click (which is not what you wanted).
I am trying to make a loop that calculates number of organisms over time, but I am stuck on how to make the loop update. Do I need to put something outside the for loop to update the total organisms?
private void calculateButton_Click(object sender, EventArgs e)
{
//declare variables for number of days passed and population
double days;
double organisms;
double increaseDaily;
double total_organisms;
//declare the constants to be used
const int interval = 1;
const int start_days = 1;
//try parse to get amount of starting organisms
if (double.TryParse(organismTextBox.Text, out organisms))
{
//try parse to get the percent daily increase
if (double.TryParse(dailyIncreaseTextBox.Text, out increaseDaily))
{
//try parse to get the number of days passed
if (double.TryParse(daysMultiplyTextBox.Text, out days))
{
//for loop to count through the number of days
for (int i = 1; i <= days; i += interval)
{
//calculate the amount of organisms
total_organisms = (organisms * (increaseDaily / 100) + organisms);
//display the amount of organisms after an amount of time
listBox1.Items.Add("after " + i + " days, the amount of organisms is " + total_organisms);
}
Each loop, you are calculating the total_organisms as the sum of organisms plus some percent:
total_organisms = (organisms * (increaseDaily / 100) + organisms);
You are never changing the value of organisms, so total_organisms will be calculated as the same value each loop. You should just updated the value of organisms instead.
Also, you could reduce indentation in your code by changing each if statement to test for parse failure and bail out:
private void calculateButton_Click(object sender, EventArgs e)
{
//declare variables for number of days passed and population
double days;
double organisms;
double increaseDaily;
List<string> errors = new List<string>();
//declare the constants to be used
const int interval = 1;
const int start_days = 1;
//try parse to get amount of starting organisms
if (!double.TryParse(organismTextBox.Text, out organisms)) {
errors.Add("Organisms must be a valid number");
}
//try parse to get the percent daily increase
if (double.TryParse(dailyIncreaseTextBox.Text, out increaseDaily)) {
errors.Add("Daily increase must be a valid number");
}
//try parse to get the number of days passed
if (double.TryParse(daysMultiplyTextBox.Text, out days)) {
errors.Add("Number of days must be a valid number");
}
if (errors.Any()) {
// Display errors to user here (depending on your UI)
return;
}
//for loop to count through the number of days
for (int i = 1; i <= days; i += interval) {
//calculate the amount of organisms
organisms = (organisms * (increaseDaily / 100) + organisms);
//display the amount of organisms after an amount of time
listBox1.Items.Add(
"after " + i + " days, the amount of organisms is " + organisms);
}
}
If you want to keep adding to the total number of organisms:
total_organisms = total_organisms + (organisms * (increaseDaily / 100) + organisms);
I have this form application project. I upload a snap of the sales field. Two datagridview are there. Bottom datagirdview contain TAX details. Contain of bottom datagrid came from database except “Amount” column. Amount column value provided by user or auto calculated. I write a code. When I try to execute it shows a error. Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index. How Can I solve it??
Snap::
Here is the code:
private void dgvSalesFooterAdd_CellStateChanged(object sender, DataGridViewCellStateChangedEventArgs e)
{
decimal Total = 0;
decimal a=Convert.ToDecimal(lblTotalAdd.Text);
for (int i = 0; i <dgvSalesFooterAdd.Rows.Count ; i++)
{
dgvSalesFooterAdd.Rows[i].Cells[4].Value = a + (a * (Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[3].Value)/100));
Total += Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[4].Value);
}
lblFinalTotalAdd.Text = Total.ToString();
}
[NOTE: Error on
dgvSalesFooterAdd.Rows[i].Cells[4].Value = a + (a * (Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[3].Value)/100));
Total += Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[4].Value);
this two lins.]
dgvSalesFooterAdd.Rows[i].Cells[4].Value = a + (a *(Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[3].Value)/100));
Total += Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[4].Value);
it will throw an exception because you are reading the value of 4th column which is null, because cell_value changed worked once you leave the cell...
got throught this link it will give you a better picture..
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellvaluechanged.aspx
and try you code like this..
void dgvSalesFooterAdd_CurrentCellDirtyStateChanged(object sender,
EventArgs e)
{
if (dgvSalesFooterAdd.IsCurrentCellDirty)
{
dgvSalesFooterAdd.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
private void dgvSalesFooterAdd_CellStateChanged(object sender, DataGridViewCellStateChangedEventArgs e)
{
decimal Total = 0;
decimal a=Convert.ToDecimal(lblTotalAdd.Text);
for (int i = 0; i <dgvSalesFooterAdd.Rows.Count ; i++)
{
dgvSalesFooterAdd.Rows[i].Cells[4].Value = a + (a * (Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[3].Value)/100));
Total += Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[4].Value);
}
lblFinalTotalAdd.Text = Total.ToString();
}
The exception is thrown when it does not find the Row index in i. You will have to reduce the number of rows by 1. This will tell the loop to count only the rows filled by values. Change the line
int i = 0; i <dgvSalesFooterAdd.Rows.Count
to
int i = 0; i <dgvSalesFooterAdd.Rows.Count - 1
Complete block will look like this;
for (int i = 0; i <dgvSalesFooterAdd.Rows.Count - 1; i++)
{
dgvSalesFooterAdd.Rows[i].Cells[4].Value = a + (a * (Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[3].Value)/100));
Total += Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[4].Value);
}