C Program to find Matrix addition,Subtraction and trace.

Write a C program to read two matrices A (MxN) and B(MxN) and perform addition ,subtraction of A and B, and Find the trace of the resultant matrix. Output the given matrix, their sum or Differences and the trace. Read more about C Programming Language .

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/

#include <stdio.h>
#include <conio.h>

void main()
{
int A[10][10], B[10][10], sumat[10][10], diffmat[10][10];
int i, j, M,N, option;

void trace (int arr[][10], int M, int N);

clrscr();

printf("Enter the order of the matrice A and Bn");
scanf("%d %d", &M, &N);

printf("Enter the elements of matrix An");
for(i=0; i<M; i++)
{
for(j=0; j<N; j++)
{
scanf("%d",&A[i][j]);
}
}

printf("MATRIX A isn");
for(i=0; i<M; i++)
{
for(j=0; j<N; j++)
{
printf("%3d",A[i][j]);
}
printf("n");
}

printf("Enter the elements of matrix Bn");
for(i=0; i<M; i++)
{
for(j=0; j<N; j++)
{
scanf("%d",&B[i][j]);
}
}

printf("MATRIX B isn");
for(i=0; i<M; i++)
{
for(j=0; j<N; j++)
{
printf("%3d",B[i][j]);
}
printf("n");
}

printf("Enter your option: 1 for Addition and 2 for Subtractionn");
scanf("%d",&option);

switch (option)
{
case 1: for(i=0; i<M; i++)
{
for(j=0; j<N; j++)
{
sumat[i][j] = A[i][j] + B[i][j];
}
}

printf("Sum matrix isn");
for(i=0; i<M; i++)
{
for(j=0; j<N; j++)
{
printf("%3d",sumat[i][j]) ;
}
printf("n");
}

trace (sumat, M, N);
break;

case 2:for(i=0; i<M; i++)
{
for(j=0; j<N; j++)
{
diffmat[i][j] = A[i][j] - B[i][j];
}
}

printf("Difference matrix isn");
for(i=0; i<M; i++)
{
for(j=0; j<N; j++)
{
printf("%3d",diffmat[i][j]) ;
}
printf("n");
}

trace (diffmat, M, N);
break;
}

} /* End of main() */

/*Function to find the trace of a given matrix and print it*/

void trace (int arr[][10], int M, int N)
{
int i, j, trace = 0;
for(i=0; i<M; i++)
{
for(j=0; j<N; j++)
{
if (i==j)
{
trace = trace + arr[i][j];
}
}
}
printf ("Trace of the resultant matrix is = %dn", trace);

}
Read more Similar C Programs
Matrix Programs
Learn C Programming

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

(c) www.c-program-example.com

One comment on “C Program to find Matrix addition,Subtraction and trace.

Leave a Reply