Addition of Matrix

Write a program to calculate addition of two given matrix

For example

Input
Matrix 1 
[1 , 4, 5]
[2 , 1, 2]
[1 , 7, 3]

Matrix 2
[1 , 4, 5]
[2 , 1, 2]
[1 , 7, 3]

Output
[2 , 8, 10]
[4 , 2, 4]
[2 , 14, 6]

Solution:

using System;

namespace AdditionMatrix
{
    class Program
    {
        static void Main()
        {
            int[,] matrix1 = {
                {3, 2, 1},
                {9, 1, 2},
                {1, 8, 2}
            };

            int[,] matrix2 = {
                {4, 9, 4},
                {3, 5, 2},
                {5, 1, 8}
            };

            var rows = matrix1.GetLength(0);
            var cols = matrix1.GetLength(1);

            var sum = new int[rows, cols];

            for (var i = 0; i < rows; i++)
            {
                for (var j = 0; j < cols; j++)
                {
                    sum[i, j] = matrix1[i, j] + matrix2[i, j];
                }
            }

            Console.WriteLine("Addition matrix: ");
            for (var i = 0; i < rows; i++)
            {
                for (var j = 0; j < cols; j++)
                {
                    Console.Write(sum[i, j] + "\t");
                }
                Console.WriteLine();
            }

            Console.ReadLine();
        }
    }
}

Leave a Reply

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