I tried to make a program which sums the elements in an array. But I have 'System.IndexOutOfRangeException' mistake on MVS. Can somebody tell where is my mistake?
public static int Sum(int[,] arr)
{
int total = 0;
for (int i = 0; i <= arr.Length; i++)
{
for (int j = 0; j <= arr.Length; j++)
{
total += arr[i,j];
}
}
return total;
}
static void Main(string[] args)
{
int[,] arr = { { 1, 3 }, { 0, -11 } };
int total = Sum(arr);
Console.WriteLine(total);
Console.ReadKey();
}
You have to get the length of each dimension (the Length property of a 2D array is the total number of items in the array) and the comparison should be <, not <=
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
total += arr[i,j];
}
}
Alternatively you can just use a foreach loop
foreach (int item in arr)
{
total += item;
}
Or even Linq
int total = arr.Cast<int>().Sum();
Try Linq
int[,] arr = { { 1, 3 }, { 0, -11 } };
int total = arr.OfType<int>().Sum();
Non Linq solution:
int total = 0;
foreach (var item in arr)
total += item;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With