Medium ยท multi-line input

Matrix Diagonal Sum

The first problem where input spans several lines: read n, then n rows, and add up the cells where the row index equals the column index.

Problem

Input: the first line is n (1 โ‰ค n โ‰ค 20). Then n lines, each with n integers separated by spaces.

Output: the sum of the main diagonal (cells where row index = column index, counting from 0).

Sample:

InputOutput
2
1 2
3 4
5

Your solution

Program.cs โ€” your solution
Custom input for "Run my input"

Judging runs entirely in your browser against hidden tests. Your code is saved locally as you type. Ctrl+Enter judges.

Stuck? Hints

Hint 1 โ€” you do not need to store the matrix

Read one row at a time and keep only the element at position i (the row's own index). The rest of the row can be discarded immediately.

Hint 2 โ€” the read loop

for (int i = 0; i < n; i++) { string[] row = Console.ReadLine().Split(' '); sum += int.Parse(row[i]); } โ€” that is the whole solution.

Solution (try first!)
string[] parts = Console.ReadLine().Split(' ');
int n = int.Parse(parts[0]);
int sum = 0;
for (int i = 0; i < n; i++)
{
    string[] row = Console.ReadLine().Split(' ');
    sum += int.Parse(row[i]);
}
Console.WriteLine(sum);

Reading one row per call to ReadLine is the standard pattern for grid problems โ€” the stream gives you a line at a time, so you process a line at a time. Next: Word Count.