Sum of upper & lower triangles elements

Sum of Upper and Lower Triangles Elements in C

To calculate the sum of the elements in the upper and lower triangles of a square matrix in C, you can follow these steps:

  1. Declare and initialize a square matrix.
  2. Iterate over the rows and columns of the matrix.
  3. For each element, check if it belongs to the upper or lower triangle.
  4. If the element belongs to the upper triangle (i.e., the column index is greater than the row index), add it to the sum of the upper triangle elements.
  5. If the element belongs to the lower triangle (i.e., the column index is less than the row index), add it to the sum of the lower triangle elements.
  6. Print the sum of the upper and lower triangle elements.

Here's an example code snippet that demonstrates this:

#include <stdio.h>

#define SIZE 3

int main() {
    int matrix[SIZE][SIZE] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

    int upperSum = 0;
    int lowerSum = 0;

    for (int i = 0; i < SIZE; i++) {
        for (int j = 0; j < SIZE; j++) {
            if (j > i) {
                upperSum += matrix[i][j];
            } else if (j < i) {
                lowerSum += matrix[i][j];
            }
        }
    }

    printf("Sum of upper triangle elements: %d\n", upperSum);
    printf("Sum of lower triangle elements: %d\n", lowerSum);

    return 0;
}

In this example, we have a 3x3 matrix with the values 1 to 9. The code calculates the sum of the upper triangle elements (2 + 3 + 6) and the sum of the lower triangle elements (4 + 7 + 8). The output will be:

Sum of upper triangle elements: 11
Sum of lower triangle elements: 19

Please note that this is just a basic example, and you can modify it to work with matrices of different sizes or adapt it to your specific requirements.