C Program To Find The Sum Of Diagonal Elements Of A Square Matrix
Finding the sum of diagonal elements in a square matrix is a fundamental operation in linear algebra and programming.
In this article, you will learn how to efficiently calculate the sum of elements along both the main and secondary diagonals of a given square matrix using C programming.
Problem Statement
Given a square matrix, the task is to calculate the sum of its diagonal elements. A square matrix has an equal number of rows and columns (e.g., an N x N matrix). There are two primary diagonals: the main diagonal (from top-left to bottom-right) and the secondary diagonal (from top-right to bottom-left).Example
Consider the following 3x3 square matrix:
1 2 3
4 5 6
7 8 9
- Main Diagonal Elements: 1, 5, 9. Sum = 1 + 5 + 9 = 15.
- Secondary Diagonal Elements: 3, 5, 7. Sum = 3 + 5 + 7 = 15.
- Sum of Both Diagonals (without correcting for overlap): (1+5+9) + (3+5+7) = 15 + 15 = 30.
- Sum of Both Diagonals (correcting for overlap): 30 - 5 = 25 (since '5' is common to both diagonals in this 3x3 matrix).
Background & Knowledge Prerequisites
To understand the solutions presented, readers should have a basic understanding of:- C programming language fundamentals (variables, data types).
- Arrays, especially two-dimensional arrays (matrices).
- Loops (for loops) for iteration.
- Basic arithmetic operations.
Use Cases or Case Studies
Summing diagonal elements is relevant in various applications:- Image Processing: Analyzing specific pixel patterns along diagonals for edge detection or feature extraction.
- Game Development: Pathfinding algorithms or collision detection in grid-based games, where movement often follows diagonal paths.
- Numerical Analysis: Operations on sparse matrices or specific matrix transformations where diagonal elements play a crucial role.
- Data Analysis: Identifying trends or anomalies in datasets represented as matrices by focusing on diagonal relationships.
- Computer Graphics: Transformations and projections often involve diagonal elements in transformation matrices.
Solution Approaches
Approach 1: Sum of Main Diagonal Elements
This approach calculates the sum of elements that lie on the main diagonal of a square matrix.
One-line summary: Iterate through the matrix where the row index i equals the column index j (i.e., matrix[i][i]) and accumulate their values.
// Sum of Main Diagonal Elements
#include <stdio.h>
int main() {
// Step 1: Define the square matrix and its size
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int size = 3; // For a 3x3 matrix
// Step 2: Initialize sum for the main diagonal
int main_diagonal_sum = 0;
// Step 3: Iterate through the matrix to find main diagonal elements
// For a main diagonal element, the row index (i) is always equal to the column index (j)
for (int i = 0; i < size; i++) {
main_diagonal_sum += matrix[i][i]; // Add element at (i, i)
}
// Step 4: Print the result
printf("Matrix:\\n");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
printf("%d ", matrix[i][j]);
}
printf("\\n");
}
printf("Sum of main diagonal elements: %d\\n", main_diagonal_sum);
return 0;
}
Sample Output:
Matrix:
1 2 3
4 5 6
7 8 9
Sum of main diagonal elements: 15
Stepwise Explanation:
- A
3x3integer matrix is initialized along with itssize. - A variable
main_diagonal_sumis set to 0 to store the cumulative sum. - A
forloop iterates fromi = 0tosize - 1. - Inside the loop,
matrix[i][i]accesses elements where the row and column indices are identical, which are precisely the elements on the main diagonal. - Each accessed element is added to
main_diagonal_sum. - Finally, the calculated sum is printed.
Approach 2: Sum of Secondary Diagonal Elements
This approach focuses on summing elements along the secondary diagonal of a square matrix.
One-line summary: Iterate through the matrix where the sum of row index i and column index j equals size - 1 (i.e., matrix[i][size - 1 - i]) and accumulate their values.
// Sum of Secondary Diagonal Elements
#include <stdio.h>
int main() {
// Step 1: Define the square matrix and its size
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int size = 3; // For a 3x3 matrix
// Step 2: Initialize sum for the secondary diagonal
int secondary_diagonal_sum = 0;
// Step 3: Iterate through the matrix to find secondary diagonal elements
// For a secondary diagonal element, the row index (i) + column index (j) = size - 1
// So, j = size - 1 - i
for (int i = 0; i < size; i++) {
secondary_diagonal_sum += matrix[i][size - 1 - i]; // Add element at (i, size-1-i)
}
// Step 4: Print the result
printf("Matrix:\\n");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
printf("%d ", matrix[i][j]);
}
printf("\\n");
}
printf("Sum of secondary diagonal elements: %d\\n", secondary_diagonal_sum);
return 0;
}
Sample Output:
Matrix:
1 2 3
4 5 6
7 8 9
Sum of secondary diagonal elements: 15
Stepwise Explanation:
- A
3x3integer matrix and itssizeare defined. - A variable
secondary_diagonal_sumis initialized to 0. - A
forloop iterates fromi = 0tosize - 1. - Inside the loop,
matrix[i][size - 1 - i]is used to access elements. Asiincreases,size - 1 - idecreases, effectively traversing the secondary diagonal (e.g., forsize=3:[0][2],[1][1],[2][0]). - Each accessed element is added to
secondary_diagonal_sum. - The final sum is printed.
Approach 3: Sum of Both Diagonals (with overlap handling)
This approach calculates the sum of elements on both the main and secondary diagonals, carefully handling cases where the center element might be counted twice.
One-line summary: Sum both main and secondary diagonal elements, then subtract the center element if the matrix size N is odd, as the center element is common to both diagonals in that scenario.
// Sum of Both Diagonals with Overlap Handling
#include <stdio.h>
int main() {
// Step 1: Define the square matrix and its size
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int size = 3; // For a 3x3 matrix
// Step 2: Initialize sum for both diagonals
int total_diagonal_sum = 0;
// Step 3: Iterate to sum elements from both diagonals
for (int i = 0; i < size; i++) {
total_diagonal_sum += matrix[i][i]; // Add main diagonal element
total_diagonal_sum += matrix[i][size - 1 - i]; // Add secondary diagonal element
}
// Step 4: Handle overlap for odd-sized matrices
// If the matrix size is odd, the center element (matrix[size/2][size/2])
// is counted twice (once for main, once for secondary diagonal).
// We need to subtract it once to get the correct unique sum.
if (size % 2 == 1) {
total_diagonal_sum -= matrix[size / 2][size / 2];
}
// Step 5: Print the result
printf("Matrix:\\n");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
printf("%d ", matrix[i][j]);
}
printf("\\n");
}
printf("Sum of both diagonal elements (with overlap handling): %d\\n", total_diagonal_sum);
return 0;
}
Sample Output:
Matrix:
1 2 3
4 5 6
7 8 9
Sum of both diagonal elements (with overlap handling): 25
Stepwise Explanation:
- A
3x3integer matrix and itssizeare defined. total_diagonal_sumis initialized to 0.- A single
forloop iterates fromi = 0tosize - 1. - Inside the loop, for each
i, bothmatrix[i][i](main diagonal) andmatrix[i][size - 1 - i](secondary diagonal) are added tototal_diagonal_sum. - After the loop, a conditional check
if (size % 2 == 1)determines if the matrix has an odd number of rows/columns. - If
sizeis odd, the middle elementmatrix[size / 2][size / 2](e.g.,matrix[1][1]forsize=3) was counted twice. It is subtracted once fromtotal_diagonal_sumto correct the sum. - The final, corrected sum is printed.
Conclusion
Calculating the sum of diagonal elements in a square matrix is a straightforward task in C, involving simple loop structures and indexing logic. Whether you need the sum of the main, secondary, or both diagonals, understanding how to correctly index matrix elements is key. The approach for summing both diagonals requires an additional check for odd-sized matrices to prevent double-counting the central element.Summary
- Main Diagonal: Elements where row index
iequals column indexj(matrix[i][i]). - Secondary Diagonal: Elements where row index
iplus column indexjequalssize - 1(matrix[i][size - 1 - i]). - Both Diagonals: Sum elements from both diagonals. If the matrix
sizeis odd, subtract the central elementmatrix[size/2][size/2]once because it is common to both diagonals and would be double-counted. - These operations are crucial in various computational tasks, from image analysis to numerical algorithms.