Reputation: 61
I have a 2d array of 7 x12. I'm stuck on how to get the sum of each column and row of it and put each result in lists, one with results of sum of each column, and other with the results of each row.
So, for columns, I thought to save the result of each column in a temp integer variable, iterating in each row with 'a' and when 'a' is equal to 12 (which is the numbers of rows), then check if 'p' (which is the number of columns) is equal to 7 and exit the loop (which means that sum of each column has been added to a new array), if not so, then the temp variable will be added to new array, the temp variable and 'a' will reset, so the loop can start again and increment p by one for get the sum of next row.
for (int a = 0; a < 12; a++)
{
int sum =+ students[a, p];
if(a == 12)
{
if (p == 7)
{
break;
}
sum_columns.Add(sum);
sum = 0;
a = 0;
p++;
}
}
Thanks guys!
Upvotes: 1
Views: 2660
Reputation: 16079
Using Linq,
public int GetSumOfColumn(int[,] matrix, int columnNumber)
{
return Enumerable.Range(0, matrix.GetLength(0))
.Select(x => matrix[x, columnNumber])
.Sum();
}
public int GetSumOfRow(int[,] matrix, int rowNumber)
{
return Enumerable.Range(0, matrix.GetLength(1))
.Select(x => matrix[rowNumber, x])
.Sum();
}
Call these functions in individual for loop, I did it for rows, you can try out the same with columns.
List<int> row_sum = new List<int>();
for(var rowIndex = 0; rowIndex < 4; rowIndex++)
{
var sum = GetSumOfRow(array, rowIndex);
row_sum.Add(sum);
}
Console.WriteLine(string.Join(Environment.NewLine, row_sum));
Implementation: .NET FIDDLE
Reference: https://www.codegrepper.com/
Upvotes: 0
Reputation: 7354
Not the most efficient, but allows you to grab a specific row or column.
class Program
{
static IEnumerable<T> GetRow<T>(T[,] someArray, int row)
{
for (int i = 0; i <= someArray.GetUpperBound(1); i++)
yield return someArray[row, i];
}
static IEnumerable<T> GetColumn<T>(T[,] someArray, int column)
{
for (int i = 0; i <= someArray.GetUpperBound(0); i++)
yield return someArray[i, column];
}
static void Main(string[] args)
{
int[,] someArray = new int[4, 2]
{
{ 1, 2 },
{ 3, 4 },
{ 5, 6 },
{ 7, 8 }
};
int rows = someArray.GetUpperBound(0) + 1;
int columns = someArray.GetUpperBound(1) + 1;
for (int i = 0; i < rows; i++)
Console.WriteLine($"Row {i} sum is {GetRow(someArray, i).Sum()}");
for (int i = 0; i < columns; i++)
Console.WriteLine($"Column {i} sum is {GetColumn(someArray, i).Sum()}");
}
}
Output:
Row 0 sum is 3
Row 1 sum is 7
Row 2 sum is 11
Row 3 sum is 15
Column 0 sum is 16
Column 1 sum is 20
Upvotes: 1
Reputation: 38785
You can simply iterate as necessary. No complex conditions or resets required:
for (int col = 0; col < 7; ++col) // iterate through the columns
{
int sum = 0;
for (int row = 0; row < 12; ++row) // iterate through the rows in the column and sum
{
sum += students[row, col];
}
sum_columns.Add(sum); // add sum to the list
}
Upvotes: 3