Tuesday, December 23, 2014

Sum & Difference of the Matrices in c pgm



Calculate the Sum & Difference of the Matrices

           #include
#include 
#include 
void readmatA();
void printmatA();
void readmatB();
void printmatB();
void sum();
void diff();
 
int a[10][10], b[10][10], sumarray[10][10], arraydiff[10][10];
int i, j, row1, column1, row2, column2;
 
void main()
{
    clrscr();
    printf("Enter the order of the matrix A \n");
    scanf("%d %d", &row1, &column1);
    printf("Enter the order of the matrix B \n");
    scanf("%d %d", &row2, &column2);
    if (row1 != row2 && column1 != column2)
    {
        printf("Addition and subtraction are possible \n");
        exit(1);
    }
    else
    {
        printf("Enter the elements of matrix A \n");
        readmatA();
        printf("matrix a is \n");
        printmatA();
        printf("Enter the elements of matrix B \n");
        readmatB();
        printf("matrix b is \n");
        printmatB();
        sum();
        diff();
    }
}
void readmatA()
{
    for (i = 0; i < row1; i++)
    {
        for (j = 0; j < column1; j++)
        {
            scanf("%d", &a[i][j]);
        }
    }
    return;
}
 
void readmatB()
{
    for (i = 0; i < row2; i++)
    {
        for (j = 0; j < column2; j++)
        {
            scanf("%d", &b[i][j]);
        }
    }
}
void printmatA()
{
    for (i = 0; i < row1; i++)
    {
        for (j = 0; j < column1; j++)
        {
            printf("%3d", a[i][j]);
        }
        printf("\n");
    }
}
 
void printmatB()
{
    for (i = 0; i < row2; i++)
    {
        for (j = 0; j < column2; j++)
        {
            printf("%3d", b[i][j]);
        }
        printf("\n");
    }
}
void sum()
{
    for (i = 0; i < row1; i++)
    {
        for (j = 0; j < column2; j++)
           {
            sumarray[i][j] = a[i][j] + b[i][j];
        }
    }
    printf("Sum matrix is \n");
    for (i = 0; i < row1; i++)
    {
        for (j = 0; j < column2; j++)
           {
            printf("%3d", sumarray[i][j]) ;
        }
        printf("\n");
    }
    return;
}
void diff()
{
    for (i = 0; i < row1; i++)
    {
        for (j = 0; j < column2; j++)
           {
            arraydiff[i][j] = a[i][j] - b[i][j];
        }
    }
    printf("Difference matrix is \n");
    for (i = 0; i < row1; i++)
    {
        for (j = 0; j < column2; j++)
        {
            printf("%3d", arraydiff[i][j]);
        }
        printf("\n");
    }
    return;
getch();
}

Output
 
Enter the order of the matrix A
3 3
Enter the order of the matrix B
3 3
Enter the elements of matrix A
1 4 5
6 7 8
4 8 9
matrix a is
  1  4  5
  6  7  8
  4  8  9
Enter the elements of matrix B
3 6 7
8 4 2
1 5 3
matrix b is
  3  6  7
  8  4  2
  1  5  3
Sum matrix is
  4 10 12
 14 11 10
  5 13 12
Difference matrix is
 -2 -2 -2
 -2  3  6
  3  3  6

No comments:

Post a Comment