How to write a C Program to calculate the sum of elements of upper triangle of a n*n matrix using Dynamic memory allocation in C Programming Language ?
Solution:/*C Program to calculate the sum of elements of upper triangle of a n*n matrix using Dynamic Memory allocation*/
#include<stdio.h>
#include<conio.h>
void main()
{
int **ip,m,n;
int sum=0,i=0,j=0;
clrscr();
printf("\nEnter the row and column: ");
scanf("%d%d",&m,&n);
ip=(int**)malloc(m*sizeof(int));
for(i=0;i<m;i++)
ip[i]=(int*)malloc(n*sizeof(int));
printf("\n");
printf("\nEnter the elements: ");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&ip[i][j]);
}
}
printf("\nEntered elements are:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("\t%d",ip[i][j]);
}
printf("\n");
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(i<=j)
sum=sum+ip[i][j];
}
}
printf("\nSum upper triangle is = %d",sum);
getch();
}
OUTPUT:
Enter the row and column:
3
3
Enter the elements:
1
2
3
4
5
6
7
8
9
Entered elements are:
1 2 3
4 5 6
7 8 9
Sum upper triangle is = 26