Header Ads

Addition, Subtraction, Multiplication and Transpose of a Matrix in C || 2D Array

A 2D array is also known as a matrix (a table of rows and columns). if you want to store data as a tabular form, like a table with rows and columns, you need to get familiar with multidimensional arrays.


Code :

#include <stdio.h>
int main()
{
int i, j, a, b, c, d, k, flag = 0, flag1 = 0;
printf("Enter rows and columns in Matrix 1 : ");
scanf("%d%d", &a, &b);
printf("Enter rows and columns in Matrix 2 : ");
scanf("%d%d", &c, &d);

int mat1[a][b], mat2[c][d], sum[a][b], sub[a][b], mul[a][d], trans1[b][a],
    trans2[d][c];

printf("Enter Elements in Matrix 1 : ");
for (i = 0; i < a; i++)
{
for (j = 0; j < b; j++)
{
scanf("%d", &mat1[i][j]);
}
}
printf("Enter Elements in Matrix 2 : ");
for (i = 0; i < c; i++)
{
for (j = 0; j < d; j++)
{
scanf("%d", &mat2[i][j]);
}
}

if (a == c && b == d)
{
flag = 1;
for (i = 0; i < a; i++)
{
for (j = 0; j < b; j++)
{
sum[i][j] = mat1[i][j] + mat2[i][j];
sub[i][j] = mat1[i][j] - mat2[i][j];
}
}
}

if (b==c)
{
flag1 = 1;
for (i = 0; i < a; i++)
{
for (j = 0; j < a; j++)
{
mul[i][j] = 0;
for (k = 0; k < a; k++)
{
mul[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
}
for (i = 0; i < a; i++)
{
for (j = 0; j < b; j++)
{
trans1[j][i] = mat1[i][j];
}
}
for (i = 0; i < c; i++)
{
for (j = 0; j < d; j++)
{
trans2[j][i] = mat2[i][j];
}
}
// Printing
if (flag == 1)
{
printf("Addition :\n");
for (i = 0; i < a; i++)
{
for (j = 0; j < b; j++)
{
printf("%d ", sum[i][j]);
}
printf("\n");
}
printf("\nSubtraction :\n");
for (i = 0; i < a; i++)
{
for (j = 0; j < b; j++)
{
printf("%d ", sub[i][j]);
}
printf("\n");
}
} else{
printf("Addition and Subtraction not Possible");
}

if (flag1 == 1)
{
printf("Multiplication :\n");
for (i = 0; i < a; i++)
{
for (j = 0; j < d; j++)
{
printf("%d ", mul[i][j]);
}
printf("\n");
}
} else{
printf("\nMultiplication not Possible");
}

printf("\nTranspose of Matrix 1 :\n");
for (i = 0; i < b; i++)
{
for (j = 0; j < a; j++)
{
printf("%d ", trans1[i][j]);
}
printf("\n");
}
printf("\nTranspose of Matrix 2 :\n");
for (i = 0; i < d; i++)
{
for (j = 0; j < c; j++)
{
printf("%d ", trans2[i][j]);
}
printf("\n");
}

return 0;
}


Output :

Enter rows and columns in Matrix 1 : 2 2
Enter rows and columns in Matrix 2 : 2 2
Enter Elements in Matrix 1 : 1 2 3 4
Enter Elements in Matrix 2 : 1 2 3 4
Addition :
2 4 
6 8 

Subtraction :
0 0 
0 0 
Multiplication :
7 10 
15 22 

Transpose of Matrix 1 :
1 3 
2 4 

Transpose of Matrix 2 :
1 3 
2 4 





Related Links :


Post a Comment

0 Comments