10. Given a square matrix, calculate the absolute difference between the sums of its diagonals.
For example, the square matrix is shown below:
1 2 3
4 5 6
9 8 9
The left-to-right diagonal = .1+5+9=15. The right to left diagonal 3+5+8 =17 . Their absolute difference is 17-15=2
using System;
using System.Collections.Generic;
using System.IO;
class Program
{
static void Main(string[] args)
{
int n = Convert.ToInt32(Console.ReadLine());
int FirstSum = 0;
int SecondSum = 0;
for (int i = 0; i < n; i++)
{
string elements = Console.ReadLine();
string[] split_header = elements.Split(' ');
int firstLineNumber = Convert.ToInt32(split_header[i]);
FirstSum += firstLineNumber;
int secondLineNumber = Convert.ToInt32(split_header[n - i - 1]);
SecondSum += secondLineNumber;
}
int result = Math.Abs(FirstSum - SecondSum);
Console.WriteLine(result);
Console.ReadLine();
}
} .
Output :
3
1 2 3
4 5 6
9 8 9
2
Other Way
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StaticConstructor
{
class Program
{public static int difference(int[,] arr, int n)
{
int d1 = 0, d2 = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
// finding sum of primary diagonal
if (i == j)
d1 += arr[i, j];
// finding sum of secondary diagonal
if (i == n - j - 1)
d2 += arr[i, j];
}
}
return Math.Abs(d1 - d2);
}
static void Main(string[] args){
int n = Convert.ToInt32(Console.ReadLine());
int i, j;
int[,] arr = new int[3, 3];
Console.Write("Input elements in the matrix :\n");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{ arr[i, j] = Convert.ToInt32(Console.ReadLine());
}
}
Console.Write(difference(arr, n));
Console.ReadLine();
}
}
}