C program to find sum of lower triangular matrix

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

Example:
If the elements of matrix are:
1 0 0
4 5 0
7 8 9
Sum of lower triangular matrix = 19

Required knowledge:

Basic C programming, For loop, Array, Matrix

Lower triangular matrix

Lower triangular matrix is a special square matrix whole all elements above the main diagonal is zero.
Lower triangular matrix

Algorithm to find sum of lower triangular matrix:

Lower triangular matrix elements is shown in the below image. We need to find sum of all elements in the red triangular area.
Lower triangular matrix elements
For any matrix A sum of lower triangular matrix elements can be defined as:
sum = sum + Aij (Where j < i).

Program:

/**
 * C program to find sum of lower 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 lower triangular matrix
     */
    for(row=0; row<3; row++)
    {
        for(col=0; col<3; col++)
        {
            if(col<row)
            {
                sum += A[row][col];
            }
        }
    }

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

    return 0;
} 
Output
Enter elements in matrix of size 3x3:
1 0 0
4 5 0
7 8 9
Sum of lower triangular matrix = 19

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment