- What are the main diagonal and secondary diagonal of a matrix
- How to find the sum of diagonal elements in a matrix
- How to handle both square and non-square matrices
- Step-by-step explanation of the program
- Practice exercises to test your understanding
Introduction
In this tutorial, we will learn how to write a C program to find the sum of diagonal elements in a matrix.
In a matrix, there are two diagonals:
- Main Diagonal: Elements where row index equals column index (i == j)
- Secondary Diagonal: Elements where row index + column index = size - 1 (i + j = n - 1)
This program is used in many real-world applications, such as:
- Image processing and computer vision
- Linear algebra and matrix operations
- Game development (checking diagonal patterns)
- Data analysis and statistics
š” Key Point: The sum of diagonal elements is only defined for square matrices (where number of rows = number of columns). For a matrix of size n Ć n, the diagonal sum includes n elements.
C Program to Find Sum of Diagonal Elements in a Matrix
#include <stdio.h>
int main() {
int rows, cols, i, j;
int main_diag_sum = 0;
int sec_diag_sum = 0;
// Ask user for matrix dimensions
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &cols);
// Check if it's a square matrix
if(rows != cols) {
printf("\nā ļø Diagonal sum is only defined for square matrices.\n");
printf("Please enter a square matrix (rows = columns).\n");
return 1;
}
// Declare matrix
int matrix[rows][cols];
// Read elements into the matrix
printf("\nEnter %d elements:\n", rows * cols);
for(i = 0; i < rows; i++) {
for(j = 0; j < cols; j++) {
printf("matrix[%d][%d] = ", i, j);
scanf("%d", &matrix[i][j]);
}
}
// Calculate sum of main diagonal (i == j)
for(i = 0; i < rows; i++) {
main_diag_sum += matrix[i][i];
}
// Calculate sum of secondary diagonal (i + j == n - 1)
for(i = 0; i < rows; i++) {
sec_diag_sum += matrix[i][rows - 1 - i];
}
// Display the matrix
printf("\nThe matrix is:\n");
for(i = 0; i < rows; i++) {
for(j = 0; j < cols; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
// Display results
printf("\nā
Sum of main diagonal elements: %d\n", main_diag_sum);
printf("ā
Sum of secondary diagonal elements: %d\n", sec_diag_sum);
printf("ā
Total sum of both diagonals: %d\n", main_diag_sum + sec_diag_sum);
return 0;
}
Sample Output
Enter the number of rows: 3 Enter the number of columns: 3 Enter 9 elements: matrix[0][0] = 1 matrix[0][1] = 2 matrix[0][2] = 3 matrix[1][0] = 4 matrix[1][1] = 5 matrix[1][2] = 6 matrix[2][0] = 7 matrix[2][1] = 8 matrix[2][2] = 9 The matrix is: 1 2 3 4 5 6 7 8 9 ā Sum of main diagonal elements: 15 ā Sum of secondary diagonal elements: 15 ā Total sum of both diagonals: 30
Another Example:
Enter the number of rows: 4 Enter the number of columns: 4 Enter 16 elements: matrix[0][0] = 1 matrix[0][1] = 2 matrix[0][2] = 3 matrix[0][3] = 4 matrix[1][0] = 5 matrix[1][1] = 6 matrix[1][2] = 7 matrix[1][3] = 8 matrix[2][0] = 9 matrix[2][1] = 10 matrix[2][2] = 11 matrix[2][3] = 12 matrix[3][0] = 13 matrix[3][1] = 14 matrix[3][2] = 15 matrix[3][3] = 16 The matrix is: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ā Sum of main diagonal elements: 34 ā Sum of secondary diagonal elements: 34 ā Total sum of both diagonals: 68
Program Explanation
Let's break down the code step by step:
- Include Header File:
#include <stdio.h>includes the standard input/output library. - Declare Variables:
int rows, cols;ā dimensions of the matrixint i, j;ā loop countersint main_diag_sum = 0;ā stores sum of main diagonalint sec_diag_sum = 0;ā stores sum of secondary diagonal
- Validate Square Matrix: Checks if
rows == cols. If not, displays an error message and exits. - Read Matrix: Uses nested loops to read elements into the matrix.
- Calculate Main Diagonal Sum: The
forloop runs fromi = 0toi = rows-1and addsmatrix[i][i]tomain_diag_sum. - Calculate Secondary Diagonal Sum: The
forloop runs fromi = 0toi = rows-1and addsmatrix[i][rows - 1 - i]tosec_diag_sum. - Display Results: Prints the matrix and the calculated sums.
- Return:
return 0;indicates successful program execution.
š Note: For odd-sized matrices, the center element is counted twice if we add both diagonals separately. To avoid this, you can use a single loop and check conditions.
Optimized Version: Single Loop
We can calculate both diagonal sums in a single loop for better efficiency:
#include <stdio.h>
int main() {
int n, i, j;
int main_diag_sum = 0;
int sec_diag_sum = 0;
printf("Enter the size of the square matrix: ");
scanf("%d", &n);
int matrix[n][n];
printf("\nEnter %d elements:\n", n * n);
for(i = 0; i < n; i++) {
for(j = 0; j < n; j++) {
printf("matrix[%d][%d] = ", i, j);
scanf("%d", &matrix[i][j]);
}
}
// Calculate both diagonals in a single loop
for(i = 0; i < n; i++) {
main_diag_sum += matrix[i][i]; // Main diagonal
sec_diag_sum += matrix[i][n - 1 - i]; // Secondary diagonal
}
// If n is odd, the center element is counted twice
// So subtract it once from the total
int total_sum = main_diag_sum + sec_diag_sum;
if(n % 2 == 1) {
int center = n / 2;
total_sum -= matrix[center][center];
}
printf("\nMatrix:\n");
for(i = 0; i < n; i++) {
for(j = 0; j < n; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
printf("\nā
Sum of main diagonal: %d\n", main_diag_sum);
printf("ā
Sum of secondary diagonal: %d\n", sec_diag_sum);
printf("ā
Total sum of both diagonals: %d\n", total_sum);
return 0;
}
Algorithm to Find Diagonal Sum
Step-by-step algorithm:
- Start
- Read the size of the square matrix (n)
- Read n Ć n elements into the matrix
- Set
main_diag_sum = 0andsec_diag_sum = 0 - For
i = 0ton-1:main_diag_sum += matrix[i][i]sec_diag_sum += matrix[i][n - 1 - i]
- If n is odd:
- Subtract the center element from the total sum to avoid double counting
- Print the matrix and diagonal sums
- End
Visual Example
For a 3Ć3 matrix:
Matrix:
1 2 3 4 5 6 7 8 9
Main Diagonal: 1 + 5 + 9 = 15
Secondary Diagonal: 3 + 5 + 7 = 15
Total Sum (without double counting center): 15 + 15 - 5 = 25
Time and Space Complexity
| Operation | Time Complexity | Space Complexity |
|---|---|---|
| Reading Matrix | O(n²) | O(1) |
| Diagonal Sum | O(n) | O(1) |
| Overall | O(n²) | O(1) |
š» Practice Exercise
Challenge 1: Find the sum of diagonal elements without using array indexing (use pointer arithmetic).
Challenge 2: Find the sum of elements above and below the main diagonal separately.
š Click to Show Solution for Challenge 2
#include <stdio.h>
int main() {
int n, i, j;
int upper_sum = 0;
int lower_sum = 0;
printf("Enter the size of the square matrix: ");
scanf("%d", &n);
int matrix[n][n];
printf("\nEnter %d elements:\n", n * n);
for(i = 0; i < n; i++) {
for(j = 0; j < n; j++) {
scanf("%d", &matrix[i][j]);
}
}
// Calculate upper and lower triangle sums
for(i = 0; i < n; i++) {
for(j = 0; j < n; j++) {
if(i < j) {
upper_sum += matrix[i][j]; // Above main diagonal
}
else if(i > j) {
lower_sum += matrix[i][j]; // Below main diagonal
}
}
}
printf("\nMatrix:\n");
for(i = 0; i < n; i++) {
for(j = 0; j < n; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
printf("\nā
Sum of elements above main diagonal: %d\n", upper_sum);
printf("ā
Sum of elements below main diagonal: %d\n", lower_sum);
return 0;
}
Frequently Asked Questions
1. What is the main diagonal of a matrix?
The main diagonal consists of elements where the row index equals the column index (i == j). For a 3Ć3 matrix, it includes elements at positions (0,0), (1,1), and (2,2).
2. What is the secondary diagonal of a matrix?
The secondary (or anti-diagonal) consists of elements where row index + column index = n - 1. For a 3Ć3 matrix, it includes elements at positions (0,2), (1,1), and (2,0).
3. How do you handle the center element when adding both diagonals?
For odd-sized matrices, the center element is counted twice. To avoid this, subtract the center element once from the total sum: total = main + sec - matrix[center][center].
4. Can we find diagonal sum without using a 2D array?
Yes, you can use a 1D array to store the matrix in row-major order and access elements using indexing: matrix[i * cols + j].
5. What if the matrix is not square?
The concept of a diagonal is only defined for square matrices. For non-square matrices, you can still access elements where row index equals column index, but it won't form a complete diagonal.
š” Tip: When working with matrices, always use nested loops to access elements. The outer loop typically controls rows, and the inner loop controls columns.