Sum main diagonal of square matrix {{1,2,3},{4,5,6},{7,8,9}} (1+5+9=15).
Ready — edit the code above and click Run.
using System;
class Program
{
static void Main()
{
int[,] m = { {1,2,3}, {4,5,6}, {7,8,9} };
int sum = 0;
for (int i = 0; i < m.GetLength(0); i++)
sum += m[i, i];
Console.WriteLine(sum);
}
}
Try solving on your own first, then reveal the official answer.
Main diagonal: indices where row equals column.