Reputation: 17
I'm currently learning C# and running into some trouble with multi dimension array.
I can't seem to figure out how to find the sum of all the elements in the array. E.g
int[,] array = { { 52, 76, 65 }, { 98, 87, 93 }, { 43, 77, 62 }, { 72, 73, 74 } };
So the sum should be:
52 + 76 + 65 + 98 + ...
I have tried to use the for loop but that just give me the sum of each array in dimension 1. E.g
private int[,] array = { { 52, 76, 33}, { 98, 87, 93 }, { 43, 77, 62 }, { 72, 73, 74 } };
public void ArraySum()
{
double sum;
for (int i = 0; i < array.GetLength(0); i++)
{
sum = 0;
for (int j = 0; j < array.GetLength(1); j++)
sum += array[i, j];
Console.WriteLine("The sums are for the array {0} is {1}: ", i, sum);
}
}
Any ideas?
Upvotes: 1
Views: 1806
Reputation: 66469
Since you're just learning and playing around anyway, you could use a List<int<int>>
to store your values instead of a 2-dimensional array, like this:
var array = new List<List<int>>
{
new List<int> {52, 76, 65},
new List<int> {98, 87, 93},
new List<int> {43, 77, 62},
new List<int> {72, 73, 74}
};
Then you could easily use LINQ to get your sum:
var sum = array.SelectMany(x => x).Sum();
If you haven't heard of it yet, you can learn more about LINQ here.
Basically, SelectMany()
flattens your multiple lists into one list, and then Sum()
just adds them all up.
Upvotes: 4
Reputation: 14059
Simply move the line sum = 0;
out of the first loop:
private int[,] array = { { 52, 76, 33}, { 98, 87, 93 }, { 43, 77, 62 }, { 72, 73, 74 } };
public void ArraySum()
{
int sum = 0;
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(1); j++)
sum += array[i, j];
}
Console.WriteLine("The sum for the whole array is {0}: ", sum);
}
In your code the sum
is reset to 0
for each sub-array.
Edit
Since the array contains int
values, consider to declare the sum
variable as int
instead of double
.
Upvotes: 3
Reputation: 24078
The other answer pointed out what's wrong with your code. Here's a short alternative to your loops using LINQ:
int[,] array = { { 52, 76, 65 }, { 98, 87, 93 }, { 43, 77, 62 }, { 72, 73, 74 } };
int sum = array.Cast<int>().Sum();
The Cast
is used to convert the multidimensional array to an IEnumerable<int>
which then allows you to use the Sum
extension method.
Upvotes: 5
Reputation: 4465
If all you want is the sum of the entire array, then
private static int[,] array = { { 52, 76, 33}, { 98, 87, 93 }, { 43, 77, 62 }, { 72, 73, 74 } };
public static void Main()
{
double sum = 0;
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(1); j++)
sum += array[i, j];
}
Console.WriteLine("The sum for the array is {0}: ", sum);
}
Upvotes: 1