Pages

Sunday, 12 July 2015

Matrix subtraction

C Program to find Matrix Subtraction
Coding:
#include<stdio.h>

int main()
{
    int a[10][10],b[10][10],c[10][10],i,j,row1,col1,row2,col2;
    printf("Enter the dimaension of first matrix:");
    scanf("%d%d",&row1,&col1);
    printf("Enter the dimaension of second matrix:");
    scanf("%d%d",&row2,&col2);
    if(row1==row2&&col1==col2)
    {
        printf("Enter the elements of the first matrix:\n");
        for(i=0;i<row1;i++)
            for(j=0;j<col1;j++)
                scanf("%d",&a[i][j]);
        printf("\nEnter the elements of the second matrix:\n");
        for(i=0;i<row2;i++)
            for(j=0;j<col2;j++)
                scanf("%d",&b[i][j]);
        printf("\nBefore subtraction:");
        printf("\nFirst matrix:");
        for(i=0;i<row1;i++)
        {
            printf("\n");
            for(j=0;j<col1;j++)
                printf("%d ",a[i][j]);
        }
        printf("\nSecond matrix:");
        for(i=0;i<row2;i++)
        {
            printf("\n");
            for(j=0;j<col2;j++)
                printf("%d ",b[i][j]);
        }
        printf("\nAfter matrix substraction:");
        for(i=0;i<row1;i++)
        {
            printf("\n");
            for(j=0;j<col1;j++)
            {
                c[i][j]=a[i][j]-b[i][j];
                printf("%d ",c[i][j]);
            }
        }
    }
    else
    {
        printf("Matrix addition not possible");
    }
    return 0;
}
Output:
Enter the dimaension of first matrix:3 3
Enter the dimaension of second matrix:3 3
Enter the elements of the first matrix:
9 8 7
6 5 4
3 2 1

Enter the elements of the second matrix:
1 2 3
1 2 3
1 1 1

Before subtraction:
First matrix:
9 8 7
6 5 4
3 2 1
Second matrix:
1 2 3
1 2 3
1 1 1
After matrix substraction:
8 6 4
5 3 1
2 1 0