# How to subtract total of each row in C# matrix from constant number and sum the result?

Hi, I would like to know how to subtract total of each row in C# matrix from a magic constant number(example : 15) and sum the result, for example, here is my current matrix

``````4 9 2
3 5 7
8 1 5``````

and the C# code of this is as below

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

namespace Formatting_Magic_Squar
{
class Program
{
static void Main(string[] args)
{
int[,] t = new int[,] { { 4 ,9, 2 }, { 3, 5, 7 }, { 8, 1, 5 } };
int[] rowSum = new int[t.GetLength(0)],
colSum = new int[t.GetLength(1)];
int sum = 0;
int magiconst = 15;
int cons = 0;
// Get the sum of each row and each column
for (int r = 0; r < t.GetLength(0); r++)
{
for (int c = 0; c < t.GetLength(1); c++)
{
rowSum[r] += t[r, c];
colSum[c] += t[r, c];
}
sum += Math.Abs(rowSum[r] - magiconst);
cons = cons + sum ;
Console.WriteLine(cons);
}
}
}
}``````

The result showing on the console is

``````0
0
1``````

Please how can sum all those result to be `0 + 0 + 1 = 1`  and return that result. Thanks.

0
: 553 At:- 7/13/2018 3:27:08 PM
c# C# matrix Subtraction

Your code is already correct, you are just not showing correct values, here is the modified code (Magic Constant =13 here)

``````using System;

namespace MatrixSubtract
{
class Program
{
static void Main(string[] args)
{
int[,] t = new int[,] {
{ 4, 9, 2 },
{ 3, 5, 7 },
{ 8, 1, 5 }
};

int[] rowSum = new int[t.GetLength(0)],
colSum = new int[t.GetLength(1)];

int sum = 0;
int magiconst = 13;
int cons = 0;
// Get the sum of each row and each column
for (int r = 0; r < t.GetLength(0); r++)
{
for (int c = 0; c < t.GetLength(1); c++)
{
rowSum[r] += t[r, c];
colSum[c] += t[r, c];
}
Console.WriteLine("Row sum: " + rowSum[r]);
sum += Math.Abs(rowSum[r] - magiconst);
Console.WriteLine("Row after subtraction: "
+ Math.Abs(rowSum[r] - magiconst)
);

//cons = cons + sum;
//Console.WriteLine(cons);
}
//show total sum here
Console.WriteLine("All rows total: "+sum);
}
}
}
``````

Output Above code shows sum of each row and subtraction from magic constant, then total sum of remainders.

1
At:- 7/14/2018 7:04:50 AM

Hi  Vikas_Jk  Thank you so much.

0
At:- 7/14/2018 4:10:27 PM

Or

Full Name *

Email *