Summary: This C program calculates the sum of boundary elements, the sum of the primary and secondary diagonals, and computes the absolute difference between the diagonals in a square matrix.
#include <stdio.h>
#include <stdlib.h>
void calculateMatrixProperties(int n, int matrix[n][n]) {
int boundary_sum = 0, primary_sum = 0, secondary_sum = 0;
// Calculate boundary sum and diagonal sums
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
// Boundary elements
if (i == 0 || i == n - 1 || j == 0 || j == n - 1) {
boundary_sum += matrix[i][j];
}
// Primary diagonal
if (i == j) {
primary_sum += matrix[i][j];
}
// Secondary diagonal
if (j == n - 1 - i) {
secondary_sum += matrix[i][j];
}
}
}
// Calculate absolute difference between the diagonals
int diagonal_diff = abs(primary_sum - secondary_sum);
// Print results
printf("Boundary sum: %d\n", boundary_sum);
printf("Diagonal difference: %d\n", diagonal_diff);
}
int main() {
int n;
// Get the size of the matrix
printf("Enter the size of the matrix: ");
scanf("%d", &n);
// Check constraints
if (n < 2 || n > 100) {
printf("Invalid matrix size! Please enter a value between 2 and 100.\n");
return 1;
}
int matrix[n][n];
// Get matrix elements
printf("Enter the matrix elements:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &matrix[i][j]);
}
}
// Calculate and print results
calculateMatrixProperties(n, matrix);
return 0;
}
Program Overview:
This program calculates properties of a square matrix such as the sum of boundary elements, the sum of diagonals, and the absolute difference between the diagonals.
calculateMatrixProperties()
:The function calculateMatrixProperties()
performs the following tasks:
i == 0 || i == n - 1 || j == 0 || j == n - 1
i == j
.j == n - 1 - i
.abs(primary_sum - secondary_sum)
.n
.n
is between 2 and 100.calculateMatrixProperties()
function is called to compute and print the required results.O(n^2)
because all elements of the matrix are traversed once.O(1)
since no additional space is used other than the matrix and constant variables.