C Program to Find Sum of All Upper Triangular Matrix Elements

  • Write a C program to find the sum of all elements in upper triangular matrix.
  • C program to add all elements of upper triangular matrix

Required Knowledge

The main diagonal of a square matrix divides it into two sections, one above the diagonal and the other one is below the diagonal. We have to find the sum of all elements in upper triangular matrix.
A matrix element matrix[i][j] is part of upper triangular matrix if i < j.

C Program to find sum of upper triangular elements of matrix

#include <stdio.h>
#include <conio.h>
 
int main(){
    int rows, cols, size, row, col, sum=0;
    int inputMatrix[50][50];
    
    printf("Enter size square matrix\n");
    scanf("%d", &size);
    rows = cols = size;
     
    printf("Enter Matrix of size %dX%d\n", rows, cols);
    /*  Input matrix*/
    for(row = 0; row < rows; row++){
        for(col = 0; col < cols; col++){
            scanf("%d", &inputMatrix[row][col]);
        }
    }
    /* 
     *  Find sum of Upper Triangular Elements 
     */
    for(row = 0; row < rows; row++){
        for(col = 0; col < cols; col++){
            if(row < col){
                /* Upper triangular matrix element*/
                sum += inputMatrix[row][col];
            }
        }
    }

    printf("Sum of Upper triangular Matrix Elements\n%d", sum);
    
    getch();
    return 0;
}
Output
Enter size square matrix
3
Enter Matrix of size 3X3
1 2 3
4 5 6
7 8 9
Sum of Upper triangular Matrix Elements
11

Related Topics
C Program to find sum of diagonal elements of matrix
C program to print lower triangular matrix
C program to print upper triangular matrix ween 1 to N
C Program to find sum of lower triangular matrix
C Program to print a matrix diagonally
C Program to find transpose of matrix
C Program to check symmetric matrix
C program to find scalar multiplication of a matrix
C program to compare two matrix
List of all C programs