0
0
CProgramBeginner · 2 min read

C Program to Find Sum of Diagonal Elements

To find the sum of diagonal elements in C, use a loop to add elements where the row and column indices are equal, like sum += matrix[i][i]; inside a loop from 0 to n-1.
📋

Examples

Input3 1 2 3 4 5 6 7 8 9
OutputSum of diagonal elements: 15
Input2 10 20 30 40
OutputSum of diagonal elements: 50
Input1 7
OutputSum of diagonal elements: 7
🧠

How to Think About It

To find the sum of diagonal elements, think of a square matrix where the diagonal elements are those with the same row and column number. You add these elements one by one by checking where the row index equals the column index.
📐

Algorithm

1
Get the size of the square matrix from the user.
2
Read the matrix elements from the user.
3
Initialize a variable sum to zero.
4
Loop through the matrix indices from 0 to size-1.
5
Add the element at position [i][i] to sum in each iteration.
6
Print the sum after the loop ends.
💻

Code

c
#include <stdio.h>

int main() {
    int n, sum = 0;
    printf("Enter size of square matrix: ");
    scanf("%d", &n);
    int matrix[n][n];

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

    for (int i = 0; i < n; i++) {
        sum += matrix[i][i];
    }

    printf("Sum of diagonal elements: %d\n", sum);
    return 0;
}
Output
Enter size of square matrix: 3 Enter matrix elements: 1 2 3 4 5 6 7 8 9 Sum of diagonal elements: 15
🔍

Dry Run

Let's trace the example with a 3x3 matrix [[1,2,3],[4,5,6],[7,8,9]] through the code.

1

Input matrix size

User inputs n = 3

2

Input matrix elements

User inputs matrix elements row-wise: 1 2 3, 4 5 6, 7 8 9

3

Initialize sum

sum = 0

4

Add diagonal elements

sum = 0 + matrix[0][0] = 0 + 1 = 1 sum = 1 + matrix[1][1] = 1 + 5 = 6 sum = 6 + matrix[2][2] = 6 + 9 = 15

5

Print result

Output: Sum of diagonal elements: 15

Iterationimatrix[i][i]sum
1011
2156
32915
💡

Why This Works

Step 1: Matrix input

We first get the size and elements of the square matrix from the user to work with actual data.

Step 2: Sum initialization

We start with sum = 0 to accumulate the diagonal elements without leftover values.

Step 3: Diagonal addition

We add elements where row and column indices are equal using sum += matrix[i][i]; to get the diagonal sum.

Step 4: Output

Finally, we print the sum to show the result to the user.

🔄

Alternative Approaches

Sum both diagonals
c
#include <stdio.h>

int main() {
    int n, sum = 0;
    printf("Enter size of square matrix: ");
    scanf("%d", &n);
    int matrix[n][n];

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

    for (int i = 0; i < n; i++) {
        sum += matrix[i][i]; // primary diagonal
        sum += matrix[i][n - i - 1]; // secondary diagonal
    }

    if (n % 2 == 1) {
        sum -= matrix[n/2][n/2]; // subtract middle element once if odd size
    }

    printf("Sum of both diagonals: %d\n", sum);
    return 0;
}
This sums both diagonals but subtracts the middle element once if matrix size is odd to avoid double counting.
Using a single loop with pointer arithmetic
c
#include <stdio.h>

int main() {
    int n, sum = 0;
    printf("Enter size of square matrix: ");
    scanf("%d", &n);
    int matrix[n][n];

    printf("Enter matrix elements:\n");
    for (int i = 0; i < n * n; i++) {
        scanf("%d", ((int *)matrix) + i);
    }

    for (int i = 0; i < n; i++) {
        sum += *(((int *)matrix) + i * (n + 1));
    }

    printf("Sum of diagonal elements: %d\n", sum);
    return 0;
}
This uses pointer arithmetic to access diagonal elements in a single loop, which is a bit advanced but efficient.

Complexity: O(n^2) time, O(n^2) space

Time Complexity

Reading the matrix requires looping through all n*n elements, which is O(n^2). Summing diagonal elements is O(n), but dominated by input reading.

Space Complexity

The matrix is stored in a 2D array of size n*n, so space complexity is O(n^2). The sum variable uses O(1) space.

Which Approach is Fastest?

All approaches require reading the full matrix, so time is similar. Pointer arithmetic may be slightly faster but less readable.

ApproachTimeSpaceBest For
Simple loop with indicesO(n^2)O(n^2)Readability and beginners
Sum both diagonalsO(n^2)O(n^2)When both diagonals needed
Pointer arithmeticO(n^2)O(n^2)Efficiency and advanced users
💡
Remember diagonal elements have the same row and column index, so use matrix[i][i] to access them.
⚠️
Beginners often forget that the matrix must be square to have a proper diagonal and try to sum diagonals in non-square matrices.