Search code examples
c#arraysfor-loopnested-loops

How can I sum the integers of a column in this 2D array?


The following code calculate the sum of each row of 'int[,] a'. What I want is to modify it so it calculates the sum per column; 1+1+1, 2+2+2, 3+3+3, 4+4+4 instead of per row. These values will be put inside 'int[] output'

static void Main(string[] args)
        {
            int[,] a = {{ 1, 2, 3, 4},
                        { 1, 2, 3, 4},
                        { 1, 2, 3, 4} };

            int[] b = SumColumn(a);
        }

 public static int[] SumColumn(int[,] a)
        {
            int[] output = new int[a.GetLength(1)];
            int sum = 0;
      
            for (int i = 0; i < a.GetLength(0); i++)
            {
                for (int j = 0; j < a.GetLength(1); j++)
                {
                    sum += a[i, j];
                }

                output[i] = sum;
                sum = 0;
            }
            return output;
        }

So i tried adding a counter and using a boolean in the nested loop (and otther methods), however it did not work for me.


Solution

  • The code is almost identical in both cases. Only the loops get flipped

        static void Main(string[] args)
        {
            int[,] a = {{ 1, 2, 3, 4},
                        { 1, 2, 3, 4},
                        { 1, 2, 3, 4} };
    
            int[] rowSums = RowSums(a);
            int[] colSums = ColumnSums(a);
    
            Console.WriteLine($"Row Sums: {string.Join(",", rowSums)}");
            Console.WriteLine($"Col Sums: {string.Join(",", colSums)}");
        }
    
        public static int[] ColumnSums(int[,] matrix)
        {
            int rowCount = matrix.GetLength(0);
            int colCount = matrix.GetLength(1);
    
            int[] result = new int[colCount];
            for (int j = 0; j < colCount; j++)
            {
                int sum = 0;
                for (int i = 0; i < rowCount; i++)
                {
                    sum += matrix[i, j];
                }
                result[j] = sum;
            }
            return result;
        }
        public static int[] RowSums(int[,] matrix)
        {
            int rowCount = matrix.GetLength(0);
            int colCount = matrix.GetLength(1);
    
            int[] result = new int[rowCount];
            for (int i = 0; i < rowCount; i++)
            {
                int sum = 0;
                for (int j = 0; j < colCount; j++)
                {
                    sum += matrix[i, j];
                }
                result[i] = sum;
            }
            return result;
        }
    

    PS. In your code there is no need to set sum=0; in the end of the outer loop, as it will get set to zero in the beginning of the next loop.

    The output should be

    Row Sums: 10,10,10
    Col Sums: 3,6,9,12