- 2074 Asoj · 4 marks
Sum of both diagonals of matrix
Short answer
For an N×N matrix, principal diagonal elements have i = j, secondary diagonal i + j = N-1. Sum both in one loop: add a[i][i] to d1 and a[i][N-1-i] to d2. For matrix 1 2 3 / 4 5 6 / 7 8 9, both sums are 15.
Write a program to read a square matrix of size N×N and find sum of both diagonals.
For an N×N matrix a[i][j]:
- Principal (main) diagonal: elements with i = j, that is a[i][i].
- Secondary diagonal: elements with i + j = N − 1, that is a[i][N−1−i].
One loop from 0 to N−1 adds both.
#include <stdio.h>
int main(void)
{
int a[10][10], n, i, j, d1 = 0, d2 = 0;
printf("Enter order N of the square matrix: ");
scanf("%d", &n);
printf("Enter %d elements:\n", n * n);
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
scanf("%d", &a[i][j]);
for (i = 0; i < n; i++) {
d1 += a[i][i]; /* principal diagonal */
d2 += a[i][n - 1 - i]; /* secondary diagonal */
}
printf("Sum of principal diagonal = %d\n", d1);
printf("Sum of secondary diagonal = %d\n", d2);
return 0;
}
Sample run (matrix 1 2 3 / 4 5 6 / 7 8 9)
Input: 3 1 2 3 4 5 6 7 8 9
Enter order N of the square matrix: Enter 9 elements:
Sum of principal diagonal = 15
Sum of secondary diagonal = 15
Main diagonal: 1 + 5 + 9 = 15; secondary diagonal: 3 + 5 + 7 = 15. (The centre element is counted in both sums when N is odd.)
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- GOTO types; sum of series program · Computer Programming, chapter 11
- Sum and average until 0 is entered · Computer Programming, chapter 5
- Sum and average between M and N using pointer · Computer Programming, chapter 9
- Sum of two matrices in FORTRAN · Computer Programming, chapter 11
- Transpose m×n matrix in FORTRAN · Computer Programming, chapter 11
- Read records until end; show nth record · Computer Programming, chapter 10 · asked 2×
- C program: sum of two 8-bit BCD numbers · Embedded System, chapter 9
- Square footing size in clay, 750 kN · Foundation Engineering, chapter 6
- Truss: flexibility matrix method · Theory of Structures II, chapter 2
- Student file read/write and modify by roll · Object Oriented Programming, chapter 8