Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C # Two-dimensional int array,Sum off all elements

Tags:

arrays

c#

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(); 
}
like image 821
akinov Avatar asked Dec 17 '25 21:12

akinov


2 Answers

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();
like image 115
juharr Avatar answered Dec 20 '25 10:12

juharr


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;
like image 40
Dmitry Bychenko Avatar answered Dec 20 '25 10:12

Dmitry Bychenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!