Answer to Question #275682 in C for Gaurav

Question #275682

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.


1
Expert's answer
2021-12-05T11:22:35-0500


#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS