Sum of upper triangle and lower triangle in C++

In this problem, we are given a matrix. Our task is to create a program to print the sum of upper triangle and lower triangle.

Lower triangle

M<sub>00                     </sub>0             0       …        0
M<sub>10                     </sub>M<sub>11               </sub>0       …        0
M<sub>20                     </sub>M<sub>21               </sub>M<sub>22      </sub>…        0
…
M<sub>row0                   </sub>M<sub>row1             </sub>M<sub>row2</sub>      … M<sub>row col</sub>

Upper triangle

M<sub>00                     </sub>M<sub>01               </sub>M<sub>02          </sub>…       M<sub>0col</sub>
0                 M<sub>11               </sub>M<sub>12          </sub>…       M<sub>1col</sub>
0                 0             M<sub>22          </sub>…       M<sub>2col</sub>
…
0                 0             0         …     M<sub>row col</sub>

Let’s take an example to understand the problem,

Input: {{5, 1, 6}
{8, 2, 0}
{3, 7, 4}}
Output: upper triangle sum = 18
lower triangle sum = 29
Explanation:
Sum of upper triangle sum = 5 + 1 + 6 + 2 + 0 + 4 = 18
Sum of lower triangle sum = 5 + 8 + 2 + 3 + 7 + 4 = 29

A simple solution to this problem. We will use loop to traverse the array in the upper triangular elements and lower triangular elements. The calculate the sum in two separate variables, lSum and uSum.

Example

Program to illustrate the working of our solution,

#include <iostream>
using namespace std;
int row = 3;
int col = 3;
void sum(int mat[3][3]) {
   int i, j;
   int uSum = 0;
   int lSum = 0;
   for (i = 0; i < row; i++)
      for (j = 0; j < col; j++) {
         if (i <= j) {
         uSum += mat[i][j];
      }
   }
   cout<<"Sum of the upper triangle is "<<uSum<<endl;
   for (i = 0; i < row; i++)
      for (j = 0; j < col; j++) {
         if (j <= i) {
            lSum += mat[i][j];
      }
   }
   cout<<"Sum of the lower triangle is "<<lSum<<endl;
}
int main() {
   int mat[3][3] = { { 5, 1, 6 },
                  { 8, 2, 0 },
                     { 3, 7, 4 }};
   sum(mat);
   return 0;
}

Output

Sum of the upper triangle is 18
Sum of the lower triangle is 29


Updated on: 2026-03-11T22:50:51+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements