Pages

Sunday, 12 July 2015

Matrix addition

C program to add two matrix
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 addition:");
        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 addition:");
        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: 1 2 3 4 5 6 7 8 9 Enter the elements of the second matrix: 9 8 7 6 5 4 3 2 1 Before addition: First matrix: 1 2 3 4 5 6 7 8 9 Second matrix: 9 8 7 6 5 4 3 2 1 After matrix addition: 10 10 10 10 10 10 10 10 10