C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Pointers in C

Matrix Trace and Sum of Diagonals using Pointers

C Program: Matrix Trace and Sum of Diagonals using Pointers

C

#include <stdio.h>

 

int main() {

    int a[10][10];

    int *p;

    int rows, cols, i, j;

    int trace = 0, sum_primary = 0, sum_secondary = 0;

 

    printf("Enter number of rows and columns (square matrix): ");

    scanf("%d %d", &rows, &cols);

 

    if (rows != cols) {

        printf("Matrix must be square to find trace and diagonals!\n");

        return 0;

    }

 

    printf("Enter elements of the matrix:\n");

    for (i = 0; i < rows; i++) {

        for (j = 0; j < cols; j++) {

            scanf("%d", &a[i][j]);

        }

    }

 

    p = &a[0][0];  // Pointer to the first element of the matrix

 

    // Calculate trace and diagonal sums using pointers

    for (i = 0; i < rows; i++) {

        sum_primary += *(p + i * cols + i);              // Primary diagonal

        sum_secondary += *(p + i * cols + (cols - i - 1)); // Secondary diagonal

    }

 

    trace = sum_primary; // Trace is same as sum of primary diagonal

 

    printf("\nMatrix:\n");

    for (i = 0; i < rows; i++) {

        for (j = 0; j < cols; j++) {

            printf("%d ", a[i][j]);

        }

        printf("\n");

    }

 

    printf("\nTrace of the Matrix: %d\n", trace);

    printf("Sum of Primary Diagonal: %d\n", sum_primary);

    printf("Sum of Secondary Diagonal: %d\n", sum_secondary);

 

    return 0;

}

Output

 
OUTPUT :
Enter number of rows and columns (square matrix): 3 3
Enter elements of the matrix:
1 2 3
4 5 6
7 8 9

Matrix:
1 2 3
4 5 6
7 8 9

Trace of the Matrix: 15
Sum of Primary Diagonal: 15
Sum of Secondary Diagonal: 15

Explanation

  1. The matrix must be square (same number of rows and columns).
  2. The trace of a matrix is the sum of its main diagonal elements.
  3. Using a pointer p, each diagonal element is accessed via pointer arithmetic:
    • Primary diagonal: *(p + i * cols + i)
    • Secondary diagonal: *(p + i * cols + (cols - i - 1))
  4. Both sums are calculated and displayed.