Challenge: Diagonal Sum
Completed
Read n and then an n × n grid of numbers (row by row). Print the sum of the main diagonal (top-left to bottom-right).
Input
n (1 ≤ n ≤ 10), then n lines of n integers.
Output
The diagonal sum.
Example
Input
3 1 2 3 4 5 6 7 8 9
Output
15
Editor
C
Hints
Read the grid with two nested loops.
Diagonal cells have the same row and column: grid[i][i].
Solution explanation
On the main diagonal the row index equals the column index, so one loop is enough to add them up.
Show solution
#include <stdio.h>
int main() {
int n;
int grid[10][10];
scanf("%d", &n);
for (int r = 0; r < n; r++) {
for (int c = 0; c < n; c++) {
scanf("%d", &grid[r][c]);
}
}
int sum = 0;
for (int i = 0; i < n; i++) {
sum += grid[i][i];
}
printf("%d\n", sum);
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module