Koray BallÄ± - 7 months ago 64
C# Question

Sum of 2 Multidimensional Arrays

I'm able to sum 2 values in one multidimensional array and print using Console Application.That code below prints 2 sums of each multidimensional arrays. But what I need is,Printing the sum of 2 multidimensional arrays.I've cleaned the code up to be less complex.

``````        int[,] a = new int[2, 2];
int[,] b = new int[2, 2];
int[,] c = new int[2, 2];

for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 1; j++)
{
Console.Write("Please enter {0}. Mark of First lesson", i + 1, j + 1);
a[i, j] = Int32.Parse(Console.ReadLine());
}
}

for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 1; j++)
{
Console.Write("Please enter {0}. Mark of Second lesson", i + 1, j + 1);
b[i, j] = Int32.Parse(Console.ReadLine());
}
}

for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 1; j++)
{
c[i, j] = a[i, j] + b[i, j];
Console.WriteLine("{0}."+c[i, j],i+1+"The sum of 2 marks is:",j+1);
}
}
``````

You dont need to do extra calculation for that. Its really very simple.

You can take two variable which will tell you the sum of each matrix and finally you can add them. Or If you want only the sum of two matrices then you can get that by one variable only.

So When you are filling your matrices just increment the respective sum by that value thats it.

``````public static void Main()
{

int[,] a = new int[2, 2];
int[,] b = new int[2, 2];
int[,] c = new int[2, 2];

int sum1 = 0;
int sum2 = 0;

for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
Console.Write("Please enter {0}. Mark of First lesson", i + 1, j + 1);
a[i, j] = Int32.Parse(Console.ReadLine());

sum1 += a[i,j];
}
}

for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
Console.Write("Please enter {0}. Mark of Second lesson", i + 1, j + 1);
b[i, j] = Int32.Parse(Console.ReadLine());
sum2 += b[i, j];
}
}

Console.WriteLine("Sum: " + (sum1 + sum2));

//for (int i = 0; i < 2; i++)
//{
//    for (int j = 0; j < 2; j++)
//    {
//        c[i, j] = a[i, j] + b[i, j];
//        Console.WriteLine("{0}." + c[i, j], i + 1 + "The sum of 2 marks is:", j + 1);
//    }
//}