Reputation: 5
Hi guys i am trying to create a retrieve method to retrieve a sum total of my 2d array values i have built the array to fill from user input but not sure how to total all array values as i am still learning.
public int[,] ToysMade = new int[4, 5];
public String[] days = new String[] { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" };
public void UserInput()
{
String value;
int numCount;
//retrieveing length of ToysMade array dimensions if less than 0 repeat untill last dimension filled
for (int i = 0; i < ToysMade.GetLength(0); i++)
{
for (int ii = 0; ii < ToysMade.GetLength(1); ii++)
{
//taking user input for array dimension 0 "first dimension" then increment it by 1 after input ready for next dimension "i + 1"
value = Microsoft.VisualBasic.Interaction.InputBox("Enter Value For " + days[ii] + " of week " + (i + 1).ToString() + " Enter Value");
try
{
//making sure for only int past through
while (!(int.TryParse(value, out numCount)))
{
MessageBox.Show("Not a valid number, please try again.");
value = Microsoft.VisualBasic.Interaction.InputBox("Enter Value for " + days[i] + " of week " + (i + 1).ToString() + " Enter Value");
}
// taking values enterd from user and set next dimension for next input by incrementing it
ToysMade[i, ii] = numCount;
}
catch (Exception e)
{
MessageBox.Show("Value enterd is not in a valid format");
}
}
}
}
Upvotes: 0
Views: 2099
Reputation: 5
Thanks guys awesome works thanks heaps again
public void Sum()
{
int total = 0;
for(int i = 0;i < ToysMade.GetLength(0); i++)
{
for(int j = 0;j < ToysMade.GetLength(1); j++)
{
total += ToysMade[i, j];
}
}
txtOutput.Text += "\r\nThe sum of products is: " + total.ToString();
}
Upvotes: 0
Reputation: 4744
You can use Linq by creating an IEnumerable<int>
from ToysMade
;
var total = ToysMade.Cast<int>().Sum();
Upvotes: 0
Reputation: 186803
I suggest put either simple foreach loop
int total = 0;
foreach (var item in ToysMade)
total += item;
or nested loops which are typical for 2d arrays
int total = 0;
for (int i = 0; i < ToysMade.GetLength(0); i++)
for (int j = 0; j < ToysMade.GetLength(1); j++)
total += ToysMade[i, j];
Upvotes: 1