Basic

Switch Case

Goto

Operators

if Statement

Nested if

While Loop

For Loop

Array

2D Array

Patterns

Excersises


C Program to Find the Sum of the Main Diagonal and Secondary Diagonal of a Square Matrix using 2D Array


Write a C program to find sum of Main and Secondary Diagonals of a Square Matrix using 2D array

  • For a square matrix (N × N)
  • Main Diagonal (Primary Diagonal): Elements where i == j .
  • Secondary Diagonal: Elements where i + j == N - 1 .
  • Prints the total diagonal sum, adjusting for the center element if matrix size is odd.
Example : pgm.c
#include <stdio.h>

int main() {
    int matrix[10][10];
    int n, mainDiagonalSum = 0, secondaryDiagonalSum = 0;

    // Input the size of the square matrix
    printf("Enter the size of the square matrix (n x n): ");
    scanf("%d", &n);

    // Input matrix elements
    printf("Enter the elements of the matrix:\n");
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            scanf("%d", &matrix[i][j]);
        }
    }

    // Calculate diagonal sums
    for (int i = 0; i < n; i++) {
        mainDiagonalSum += matrix[i][i];                   // main diagonal
        secondaryDiagonalSum += matrix[i][n - 1 - i];      // secondary diagonal
    }

    // If matrix is odd-sized, subtract middle element once (counted twice)
    if (n % 2 == 1) {
        int middle = matrix[n / 2][n / 2];
        printf("Middle element (counted twice): %d\n", middle);
        printf("Sum of diagonals: %d\n", mainDiagonalSum + secondaryDiagonalSum - middle);
    } else {
        printf("Sum of main diagonal: %d\n", mainDiagonalSum);
        printf("Sum of secondary diagonal: %d\n", secondaryDiagonalSum);
        printf("Total sum of diagonals: %d\n", mainDiagonalSum + secondaryDiagonalSum);
    }

    return 0;
}

Output:

Enter the size of the square matrix (n x n): 3
Enter the elements of the matrix:
1 2 3
4 5 6
7 8 9
Middle element (counted twice): 5
Sum of diagonals: 25

Explanation:

  • Main Diagonal → 1 + 5 + 9 = 15 .
  • Secondary Diagonal → 3 + 5 + 7 = 15 .
  • Total Sum → 15 + 15 = 30
    (If the matrix has an odd size, the center element is counted twice, so we subtract it once.)