Given a square matrix of size N*N, print the sum of upper and lower triangular elements. Upper Triangle consists of elements on the diagonal and above it. The lower triangle consists of elements on the diagonal and below it.
#include <stdio.h>
void calculateSum(int squareMatrix[3][3], int N)
{
int i, j;
int sumUpperTriangle = 0;
int sumLowerTriangle = 0;
//to calculate sum of upper triangle
for (i = 0; i < N; i++){
for (j = 0; j < N; j++) {
if (i <= j) {
sumUpperTriangle += squareMatrix[i][j];
}
}
}
//to calculate sum of lower triangle
for (i = 0; i < N; i++){
for (j = 0; j < N; j++) {
if (j <= i) {
sumLowerTriangle += squareMatrix[i][j];
}
}
}
printf("Upper triangle:\n");
for (i = 0; i < N; i++){
for (j = N-1; j >= 0; j--){
if (i <= j) {
printf("%d ",squareMatrix[i][j]);
}
}
printf("\n");
}
printf("\nLower triangle:\n");
for (i = 0; i < N; i++){
for (j = 0; j < N; j++) {
if (j <= i) {
printf("%d ",squareMatrix[i][j]);
}
}
printf("\n");
}
printf("\nThe sum of upper triangle is %d\n", sumUpperTriangle);
printf("The sum of lower triangle is %d\n", sumLowerTriangle);
}
int main()
{
const int N = 3;
int squareMatrix[3][3] = {{ 7, 9, 4 },{ 2, 1, 2 },{ 8,8, 4 }};
calculateSum(squareMatrix,N);
getchar();
getchar();
return 0;
}
Comments
Leave a comment