#include
int main() {
int n, i, j, sum = 0;
// Get the size of the square matrix
printf("Enter the size of the square matrix: ");
scanf("%d", &n);
// Declare a 2D array to store the matrix elements
int matrix[n][n];
// Get the matrix elements from the user
printf("Enter the elements of the matrix:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &matrix[i][j]);
}
}
// Calculate the sum of the diagonals
for (i = 0; i < n; i++) {
// Sum of the primary diagonal (top-left to bottom-right)
sum += matrix[i][i];
// Sum of the secondary diagonal (top-right to bottom-left)
sum += matrix[i][n - i - 1];
}
// Print the sum of the diagonals
printf("Sum of all diagonals of the matrix: %d\n", sum);
return 0;
}
```
Explanation:
1. Include Header: `#include 2. Declare Variables:
- `n`: Stores the size of the square matrix.
- `i`, `j`: Loop counters for iterating through the matrix.
- `sum`: Stores the sum of the diagonal elements.
3. Get Matrix Size: The code prompts the user to enter the size of the square matrix and stores it in `n`.
4. Declare Matrix: A 2D array `matrix` is declared to store the matrix elements. The size is `n x n`.
5. Input Matrix Elements: The code takes the matrix elements as input from the user and stores them in the `matrix` array.
6. Calculate Diagonal Sum:
- The code uses nested loops to iterate through the matrix.
- Inside the loops, it adds the element at `matrix[i][i]` to `sum`, which corresponds to the primary diagonal (top-left to bottom-right).
- It also adds the element at `matrix[i][n - i - 1]` to `sum`, which corresponds to the secondary diagonal (top-right to bottom-left).
7. Print Sum: Finally, the code prints the `sum` of the diagonals to the console.
Example:
Input:
```
Enter the size of the square matrix: 3
Enter the elements of the matrix:
1 2 3
4 5 6
7 8 9
```
Output:
```
Sum of all diagonals of the matrix: 25
```
In this example, the sum of the diagonals (1+5+9 + 3+5+7) is 25.