C program to calculate sum of Upper Triangular Elements in C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | #include<stdio.h> #include<conio.h> int main() { int i, j, a[10][10], sum, rows, columns; printf("\nEnter the number of Rows : "); scanf("%d", &rows); printf("\nEnter the number of Columns : "); scanf("%d", &columns); //Accept the Elements in Matrix for (i = 0; i < rows; i++) for (j = 0; j < columns; j++) { printf("\nEnter the Element a[%d][%d] : ", i, j); scanf("%d", &a[i][j]); } //Addition of all Diagonal Elements sum = 0; for (i = 0; i < rows; i++) for (j = 0; j < columns; j++) { // Condition for Upper Triangle if (i < j) { sum = sum + a[i][j]; } } //Print out the Result printf("\nSum of Upper Triangle Elements : %d", sum); return (0); } |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | Enter the number of Rows : 3 Enter the number of Columns : 3 Enter the Element a[0][0] : 1 Enter the Element a[0][1] : 2 Enter the Element a[0][2] : 3 Enter the Element a[1][0] : 2 Enter the Element a[1][1] : 1 Enter the Element a[1][2] : 1 Enter the Element a[2][0] : 1 Enter the Element a[2][1] : 2 Enter the Element a[2][2] : 1 Sum of Upper Triangle Elements : 6 |
Explanation :
Considering above 3×3 matrix -
- By Observing , it is clear that when i < j Condition is true then and then only we have to add the elements
Download Program : [ Click Here ]