Monday, April 27, 2020

Addition of two User Defined Square Matrix in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication
{
    class MatrixAdd
    {
        public static void Main()
        {
            Console.WriteLine("Enter Row and Columns for First Matrix separated by single space");
            int rows, cols;
            string strRowsCols = Console.ReadLine();
            rows = int.Parse(strRowsCols.Substring(0, 1));
            cols = int.Parse(strRowsCols.Substring(2, 1));
            int j = 0;

            int[,] MatrixLength = new int[rows, cols];

            Console.WriteLine("Enter First Matrix Elements in Matrix Form");
            for (int i = 0; i < rows; i++)
            {
            int[] intArrays = Array.ConvertAll(Console.ReadLine().Split(' '), a => int.Parse(a));

                foreach (var k in intArrays)
                {
                    MatrixLength[i, j] = k;
                    j = j + 1;
                }
                j = 0;
            }

        Console.WriteLine("Enter Row and Columns for Second Matrix separated by single space");
            strRowsCols = Console.ReadLine().Trim();
            rows = int.Parse(strRowsCols.Substring(0, 1));
            cols = int.Parse(strRowsCols.Substring(2, 1));


            int[,] MatrixLength1 = new int[rows, cols];
            Console.WriteLine("Enter Second Matrix Elements in Matrix Form");
            j = 0;
            for (int i = 0; i < rows; i++)
            {
            int[] intArrays = Array.ConvertAll(Console.ReadLine().Split(' '), a => int.Parse(a));

                foreach (var k in intArrays)
                {
                    MatrixLength1[i, j] = k;
                    j = j + 1;
                }
                j = 0;
            }

           Console.WriteLine("Addition of above two Matrix");
            for (int k = 0; k < rows; k++)
            {
                for (int l = 0; l < cols; l++)
                {
                    if (l < cols - 1)
                        Console.Write("{0} ", MatrixLength[k, l] + MatrixLength1[k, l]);
                    else
                        Console.Write("{0}", MatrixLength[k, l] + MatrixLength1[k, l]);
                }

                if (k < rows - 1)
                    Console.WriteLine();
            }

            Console.Read();
        }
    }
}

First Output :



Second Output :



No comments:

Post a Comment