- 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
- C printf and scanf functions
- Two dimensional matrix in C
- For loop in C
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