Here is the C program to find the sum of all elements in upper triangular matrix. 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.
Required Knowledge
C Program to find sum of upper triangular elements of matrix
#include <stdio.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]); } } 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); 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