In this C program, We will show “How to build logic to calculate the sum of Upper and Lower Triangle of a Matrix ” . We, also see, “How to print the sum of Upper and Lower Triangle of a Matrix by taking and without taking user input”. So, let’s do it …
Sum Upper and Lower Triangle of a Matrix Without Taking User Input
#include<stdio.h>
int main()
{
int A[3][3] = {{1,2,3},{4,5,6},{7,8,9}}, i, j,upperSum=0,lowerSum=0;
//Printing the A matrix.
printf("A Matrix is: \n");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
printf("%d ",A[i][j]);
}
printf("\n");
}
// Applying Condition to Sum the Diagonal of A matrix.
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
if(i<j)
upperSum = upperSum + A[i][j];
if(i>j)
lowerSum = lowerSum + A[i][j];
}
printf("\n");
}
printf("The upperSum of Diagonal Elements is %d \n\n", upperSum);
printf("The lowerSum of Diagonal Elements is %d \n\n", lowerSum);
return 0;
}
Sum Upper and Lower Triangle of a Matrix by Taking the User Input
#include<stdio.h>
int main()
{
int A[10][10], i, j, rows,colm, upperSum=0, lowerSum=0;
printf("Enter the rows and column of the A Matrix: ");
scanf("%d %d", &rows, &colm);
while(rows!=colm)
{
printf("\nSorry! Enter the same amount of rows and column. \n");
printf("Enter the rows and column of the A Matrix: ");
scanf("%d %d", &rows, &colm);
}
//Getting user Input of A Matrix.
for(i=0; i<rows; i++)
{
for(j=0; j<colm; j++)
{
printf("Enter A[%d][%d] : ",i,j);
scanf("%d", &A[i][j]);
}
printf("\n");
}
//Printing the A matrix.
printf("A Matrix is: \n");
for(i=0; i<rows; i++)
{
for(j=0; j<colm; j++)
{
printf("%d ",A[i][j]);
}
printf("\n");
}
// Applying Condition to Sum the Diagonal of A matrix.
for(i=0; i<rows; i++)
{
for(j=0; j<colm; j++)
{
if(i<j)
upperSum = upperSum + A[i][j];
if(i>j)
lowerSum = lowerSum + A[i][j];
}
printf("\n");
}
printf("The upperSum of Diagonal Elements is %d \n\n", upperSum);
printf("The lowerSum of Diagonal Elements is %d \n\n", lowerSum);
return 0;
}
Keep Learning with PrologiCode.
Happy Coding.