c# - Sum of all numbers in a multi-dimensional array -
c# - Sum of all numbers in a multi-dimensional array -
i'm learning c# , running problem multi dimension array.
i can't seem figure out how find sum of elements in array. e.g
int[,] array = { { 52, 76, 65 }, { 98, 87, 93 }, { 43, 77, 62 }, { 72, 73, 74 } };
so sum should be:
52 + 76 + 65 + 98 + ...
i have tried utilize loop give me 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; (int = 0; < array.getlength(0); i++) { sum = 0; (int j = 0; j < array.getlength(1); j++) sum += array[i, j]; console.writeline("the sums array {0} {1}: ", i, sum); } }
any ideas?
simply move line sum = 0;
out of first loop:
private int[,] array = { { 52, 76, 33}, { 98, 87, 93 }, { 43, 77, 62 }, { 72, 73, 74 } }; public void arraysum() { int sum = 0; (int = 0; < array.getlength(0); i++) { (int j = 0; j < array.getlength(1); j++) sum += array[i, j]; } console.writeline("the sum whole array {0}: ", sum); }
in code sum
reset 0
each sub-array.
edit since array contains int
values, consider declare sum
variable int
instead of double
.
c# multidimensional-array
Comments
Post a Comment