This website completely moved to new platform. For latest content, visit www.programmingposts.com

Search this Site

26 Jan 2013

C PROGRAM TO PERFORM SUBTRACTION ON MATRICES


C PROGRAM TO PERFORM SUBTRACTION ON TWO MATRICES


#include<stdio.h>
#include<conio.h>
void main()
{
//using 2D-ARRAYS
int RowSize,ColSize;
int Matrix1[5][5];
int Matrix2[5][5];
int ResultMatrix[5][5];
int i, j;
printf("\n >>> PROGRAM To PERFORM SUBTRACTION ON TWO MATRICES <<<\n");
printf("\n Enter the Size of a Matrix(For Example:3 3) : ");
scanf("%d %d",&RowSize,&ColSize);

if (RowSize > 5 || ColSize > 5) //limiting the size of matrix
{
printf(" The Size Of Matrix should Be in Less Than 5 (limiting size of array)");
printf("\n\n\t Press Enter key to exit....");
getch();
return;
}

else
{
//Initializing all the elements to zero
for (i = 0; i < RowSize; i++)
{
for (j = 0; j < ColSize; j++)
{
Matrix1[i][j] = 0;
Matrix2[i][j] = 0;
}
}
//Reading elements of Matrix1
printf("\n Enter the elements of Matrix1(%d * %d) \n", RowSize, ColSize);
for (i = 0; i < RowSize; i++)
{
for (j = 0; j < ColSize; j++)
{
printf(" Matrix1[%d][%d] : ", i, j);
scanf("%d",&Matrix1[i][j]);
}
}

//Reading elements of Matrix2
printf("\n Enter the elements of Matrix2(%d * %d) \n", RowSize, ColSize);
for (i = 0; i < RowSize; i++)
{
for (j = 0; j < ColSize; j++)
{
printf(" Matrix2[%d][%d] : ", i, j);
scanf("%d",&Matrix2[i][j]);
}
}

//calculating ResultMatrix, by Subtracting Matrix2 from Matrix1
for (i = 0; i < RowSize; i++)
{
for (j = 0; j < ColSize; j++)
{
ResultMatrix[i][j] = Matrix1[i][j] - Matrix2[i][j];
}
}

//Printing Result Matrix
printf("\n\n\t*** Result Matrix ***\n\n\t");
for (i = 0; i < RowSize; i++)
{
for (j = 0; j < ColSize; j++)
{
if (ResultMatrix[i][j] > 0 && ResultMatrix[i][j] < 10)
{
//prinnting number as 01,02,etc,.
printf("0%d ",ResultMatrix[i][j] );
}
else
{
printf("%d ",ResultMatrix[i][j]);
}

if (j == ColSize - 1) { printf("\n\t"); }

}
}
}

printf("\n\n\t Press Enter key to exit....");
getch();
}

Output1 :
                    
Output2: 


For C# program :

C# PROGRAM TO PERFORM SUBTRACTION ON MATRICES USING ARRAYS