Sum of row and column of a matrix

Write a Program to compute the sum of row and each column of a matrix

For example:

Input:
[1,4,7]
[2,5,8]
[3,6,9]

Output
90

Sum of each row and column i.e. 12+15+18+6+15+24

Solution

using System;

namespace MatrixSum
{
    class Program
    {
        static void Main()
        {
            int[,] a = {
                {1, 4, 7},
                {2, 5, 8},
                {3, 6, 9}
            };

            var rows = a.GetLength(0);
            var cols = a.GetLength(1);
            var total = 0;
            for (var i = 0; i < rows; i++)
            {
                var sumRow = 0;
                for (var j = 0; j < cols; j++)
                {
                    sumRow += a[i, j];
                }

                total += sumRow;
                Console.WriteLine($"Row {i + 1} : {sumRow}" );
            }

            for (var i = 0; i < cols; i++)
            {
                var sumCol = 0;
                for (var j = 0; j < rows; j++)
                {
                    sumCol += a[j, i];
                }
                total += sumCol;
                Console.WriteLine($"column{i + 1} :{sumCol} ");
            }
            Console.WriteLine($"Sum of matrix is {total}");
            Console.ReadLine();
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *