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);
}
Console.ReadKey();
}
}
}
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.
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);
Console.ReadKey();
}
}
}
Output
Above code shows sum of each row and subtraction from magic constant, then total sum of remainders.
Hi Vikas_Jk Thank you so much.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly