C program to find sum of upper triangular matrix

Write a C program to read elements in a matrix and find sum of upper triangular matrix. How to find sum of upper triangular matrix in C.

Example: If elements of the matrix are:
1 2 3
0 5 6
0 0 9

Sum of upper triangular matrix = 11

Required knowledge:

Basic C programming, For loop, Array, Matrix

Upper triangular matrix

Upper triangular matrix is a special type of square matrix whose all elements below main diagonal is zero.
Upper triangular matrix

Algorithm to find sum of upper triangular matrix:

Upper triangular matrix elements can be described as below image we need to find sum of elements inside red triangle.
Upper triangular matrix elements

We can easily find sum of all elements matrix A inside the red triangular area i.e.
sum = sum + Aij (Where i<j).

Program:

/**
 * C program to find sum of upper triangular matrix
 */

#include <stdio.h>

int main()
{
    int A[3][3];
    int row, col, sum = 0;
    
    /*
     * Reads elements in matrix from user
     */
    printf("Enter elements in matrix of size 3x3: \n");
    for(row=0; row<3; row++)
    {
        for(col=0; col<3; col++)
        {
            scanf("%d", &A[row][col]);
        }
    }
    
    /*
     * Finds sum of upper triangular matrix
     */
    for(row=0; row<3; row++)
    {
        for(col=0; col<3; col++)
        {
            if(col>row)
            {
                sum += A[row][col];
            }
        }
    }

    printf("Sum of upper triangular matrix = %d", sum);

    return 0;
} 
Output
Enter elements in matrix of size 3x3:
1 2 3
0 5 6
0 0 9
Sum of upper triangular matrix = 11

Happy coding ;)


You may also like

Labels: , , ,