Develop a C program to find a lower triangular matrix of a given matrix A and a
ID: 3676786 • Letter: D
Question
Develop a C program to find a lower triangular matrix of a given matrix A and a product of all diagonal elements of A. Lower triangular matrix is a 2D array such that every elements above the main diagonal = 0. Your program must be written using loops such that it works with any given SIZE of a matrix and should use the following prototypes:
#define SIZE 3 //Change this to match the size of matrix used in main()
//this function is to create lower triangular matrix of A (create A_lower)
void findLower(double A[][SIZE], double A_lower[][SIZE]);
//this function is to find product of all diagonal elements
void ProductDiagonal(double x[][SIZE], double *product);
//this function is to print 2D array x in a matrix format
void PrintMatrix(double x[][SIZE]);
Explanation / Answer
#include<stdio.h>
#define SIZE 3
void PrintMatrix(double x[][SIZE]);
void findLower(double x[][SIZE], double A_lower[][SIZE])
{
int rows,i,j,f;
f=1;
rows=sizeof x[0]/sizeof (double);
printf(" %d ",rows);
for(i=0;i<rows;i++)
{
for(j=0;j<SIZE;j++)
{
A_lower[i][j]=0;
}
}
for(i=0;i<rows;i++)
{
for(j=0;j<SIZE;j++)
{
if(i<j)
{
if(x[i][j]!=0)
{
printf("given matrix is not lower traingle: ");
f=0;
break;
}
}
}
if(f==0)
{
break;
}
}
if(f!=0)
{
for(i=0;i<rows;i++)
{
for(j=0;j<SIZE;j++)
{
if(i>j)
{
A_lower[i][j]=x[i][j];
}
}
}
}
PrintMatrix(A_lower);
}
void ProductDiagonal(double x[][SIZE], double *product)
{
int i,j,rows;
rows = sizeof x[0]/ sizeof (double);
for(i=0;i<rows;i++)
{
for(j=0;j<SIZE;j++)
{
if(i==j)
{
(*product)=(*product)*(x[i][j]);
}
}
}
printf(" %lf",*product);
}
void PrintMatrix(double x[][SIZE])
{
int rows = sizeof x[0]/ sizeof (double);
int i,j;
printf(" ");
for(i=0;i<rows;i++)
{
for(j=0;j<SIZE;j++)
{
printf("%lf ",x[i][j]);
}
printf(" ");
}
}
int main()
{
int i,j;
int m,n;
double element;
double x[SIZE][SIZE];
double A_lower[SIZE][SIZE];
double *product;
printf("enter size of matrix");
printf("enter no of rows:");
scanf("%d",&m);
printf("enter no of cols:");
scanf("%d",&n);
printf("enter matrix elements:");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%lf",&element);
x[i][j]=element;
}
}
findLower(x, A_lower);
//ProductDiagonal(x,product);
printf(" ");
PrintMatrix(x);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.