Answer to Question #288618 in C for candy

Question #288618

Create a C program that creates a 4x4 2d array, fill it with user-defined values and display (separately) the sum of the diagonal as well as the upper and lower triangular elements.


d ut ut ut

Lt d ut ut

Lt Lt d ut

Lt Lt Lt d


where:

ut=upper triangular

Lt=lower triangular

d=diagonal elements


1
Expert's answer
2022-01-19T01:54:56-0500
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
/*
	Create a C program that creates a 4x4 2d array, fill it with user-defined values and display (separately) 
	the sum of the diagonal as well as the upper and lower triangular elements.
*/
#define ROW	4
#define COL	4
int main()
{
	int A[ROW][COL] = {
					{1,2,3,4},
					{3,4,5,6},
					{4,5,6,7},
					{8,9,1,4}
					};
	int r,c,u=0,v=0;
	
	printf("\nInput Matrix\n");
	for(r=0;r<ROW;r++)
	{
		for(c=0;c<COL;c++)
		{
			printf("%5d",A[r][c]);
		}
		printf("\n");
	}


	printf("\n\tDiagonal Elements: (From Left to Right) \t");	
	for(r=0;r<ROW;r++)
	{
		for(c=0;c<COL;c++)
		{
			if(r==c) {u = u+A[r][c]; printf("%4d",A[r][c]);}
		}
	}
	printf("\tSum = %d",u);
	
	printf("\n\tDiagonal Elements: (Frome Right to Left)\t");	
	c=COL-1;u=0;
	for(r=0;r<ROW;r++)
	{
		u = u+A[r][c]; printf("%4d",A[r][c]);
		c--;
	}
	printf("\tSum = %d",u);
	
	printf("\n\tLower Triangular:\n");	
	u=0;c=1;
	for(r=0;r<ROW;r++)
	{
		for(v=0;v<c;v++) {printf("%5d",A[r][v]); u = u+A[r][v];}
		printf("\n");
		c++;
	}
	printf("\tSum = %d",u);
	
	printf("\n\n\tUpper Triangular:\n");	
	u=0;c=1;
	for(r=0;r<ROW;r++)
	{
		for(v=0;v<c;v++) {printf("%5d",A[r][COL-1-v]); u = u+A[r][COL-1-v];}
		printf("\n");
		c++;
	}
	printf("\tSum = %d",u);
	
}

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