Cranes at VIIT Q3

Matrix Boundary Sum and Diagonal Difference

Write a C program that computes the sum of boundary elements and the absolute difference between the diagonals of a square matrix.

Problem Statement:

Input Format:

Output Format:

Example Inputs & Outputs:

Enter the size of the matrix: 3
Enter the matrix elements:
1 2 3
4 5 6
7 8 9
Boundary sum: 40
Diagonal difference: 0
            
Enter the size of the matrix: 4
Enter the matrix elements:
5 8 12 3
7 11 4 9
10 6 14 2
3 9 8 15
Boundary sum: 91
Diagonal difference: 29
            

Constraints:

Hint:

To solve this problem, follow these steps:

  1. Take Matrix Input:
    • Read an integer n representing the size of the matrix.
    • Read a matrix of size n x n using nested loops.
  2. Calculate Boundary Sum:
    • Sum elements from the first and last rows:
      for (j = 0; j < n; j++) {
          boundary_sum += matrix[0][j] + matrix[n-1][j];
      }
    • Sum elements from the first and last columns (excluding corners to avoid double counting):
      for (i = 1; i < n-1; i++) {
          boundary_sum += matrix[i][0] + matrix[i][n-1];
      }
  3. Calculate Diagonal Sums:
    • Sum elements of the primary diagonal:
      for (i = 0; i < n; i++) {
          primary_sum += matrix[i][i];
      }
    • Sum elements of the secondary diagonal:
      for (i = 0; i < n; i++) {
          secondary_sum += matrix[i][n-1-i];
      }
  4. Calculate Absolute Difference:
    • Compute the absolute difference between the diagonals:
      diagonal_diff = abs(primary_sum - secondary_sum);
  5. Print Results:
    • Print the boundary sum.
    • Print the absolute difference between diagonal sums.

Formula Breakdown:

Task: Implement the above logic and write a C program to calculate the boundary sum and diagonal difference.