This C# Program Finds the Sum of the Values on Diagonal of the Matrix. Here the number of rows and columns are first obtained and the sum is calculated by adding the diagonal elements.

Here is source code of the C# Program to Find the Sum of the Values on Diagonal of the Matrix. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

`/*`

`* C# Program to Find the Sum of the Values on`

`* Diagonal of the Matrix`

`*/`

using System;

using System.Collections.Generic;

using System.Text;

`class mat`

`{`

int i, j, m, n;

int[,] a = new int[20, 20];

public void get()

`{`

Console.WriteLine("Enter Row Value");

m = int.Parse(Console.ReadLine());

Console.WriteLine("Enter Column Value");

n = int.Parse(Console.ReadLine());

Console.WriteLine("Enter Elements one by one");

for (i = 1; i <= m; i++)

`{`

for (j = 1; j <= n; j++)

`{`

a[i, j] = int.Parse(Console.ReadLine());

`}`

`}`

Console.WriteLine("Given Matrix");

for (i = 1; i <= m; i++)

`{`

for (j = 1; j <= n; j++)

`{`

Console.Write("\t{0}", a[i, j]);

`}`

Console.WriteLine();

`}`

`}`

public void diag()

`{`

int d;

d = 0;

if (m == n)

`{`

for (i = 1; i <= m; i++)

`{`

for (j = 1; j <= n; j++)

`{`

if (i == j)

`{`

d = d + a[i, j];

`}`

`}`

`}`

Console.WriteLine("Diagonal Sum= {0}", d);

`}`

`else`

`{`

Console.WriteLine("Can't Perform Diagonal Sum");

`}`

`}`

`class matsum`

`{`

static void Main(string[] args)

`{`

mat ma = new mat();

ma.get();

ma.diag();

Console.Read();

`}`

`}`

`}`

Here is the output of the C# Program:

Enter Row Value : 2 Enter Column Value : 2 Enter Elements One by One : 2 2 2 2 Given Matrix : 2 2 2 2 Diagonal Sum :4

**Sanfoundry Global Education & Learning Series – 1000 C# Programs.**

If you wish to look at all C# Programming examples, go to 1000 C# Programs.