A Learning Platform

SUCCESS

Success = Discipline + Consistency + Sacrifice.
Discipline - in what you do.
Consistency - in what you do.
Sacrifice - for what you do.

                   -- Manjunatha C. P. --

Addition and Subtraction of Matrices – C Program

To add or subtract 2 matrices, the order of matrices must be same. That is the rows and columns of first matrix must be equal to rows and columns of second matrix.

Suppose the order of matrix A is 3*2, the order of matrix B must also be 3*2. Then the sum or difference matrix order will also be 3*2.

A(rows, columns) = B( rows, columns)

Description:

i and j – Loop control variables.
r – Number of rows of matrix.
c – Number of columns of matrix.
r * c – Order of matrix.
a – First matrix.
b – Second matrix.
sum – Addition matrix.
dif – Subtraction matrix.
a, b, sum and dif are 2-D Arrays in C.
for loops are used to take input and print arrays.
Input : Number of rows and columns of matrix, 2 matrices a and b.
Output : Addition and Subtraction matrix.

Program: Addition and Subtraction of Matrix in C

#include<stdio.h>
#include<conio.h>
void main(){
    int a[10][10],b[10][10],sum[10][10],dif[10][10], r, c,i,j;
    printf("Enter the number of rows and columns of matrix:\n");
    scanf("%d %d",&r,&c);
    printf("Enter the elements of first matrix: \n");
    for(i=0;i<r;i++)
        for(j = 0;j<c;j++)
            scanf("%d",&a[i][j]);
    printf("Enter the elements of second matrix: \n");
    for(i=0;i<r;i++)
        for(j = 0;j<c;j++)
            scanf("%d",&b[i][j]);
    printf("The addition of two matrices is: \n");
        for(i=0;i<r;i++)
            for(j = 0;j<c;j++)
                sum[i][j]=a[i][j] + b[i][j];
    for(i=0;i<r;i++){
        for(j = 0;j < c;j++)
                printf(" %d \t ",sum[i][j]);
            printf("\n");
        }
    printf("The subtraction of two matrices is: \n");
        for(i=0;i<r;i++)
            for(j = 0;j<c;j++)
                dif[i][j]=a[i][j] - b[i][j];
    for(i=0;i<r;i++){
        for(j = 0;j < c;j++)
                printf(" %d \t ",dif[i][j]);
            printf("\n");
        }
    getch();
}

Output 1:

Enter the number of rows and columns of matrix:
2 2
Enter the elements of first matrix:
2 2
3 3
Enter the elements of second matrix:
1 1
2 2
The addition of two matrices is:
3 3
5 5
The substraction of two matrices is:
1 1
1 1

Output 2:

Enter the number of rows and columns of matrix:
2 3
Enter the elements of first matrix:
3 2 1
5 4 8
Enter the elements of second matrix:
1 9 5
-2 5 0
The addition of two matrices is:
4 11 6
3 9 8
The subtraction of two matrices is:
2 -7 -4
7 -1 8


QUIZ:

1] To add or subtract the order of matrices must be same.
  1. TRUE
  2. FALSE
2] To multiply the order of matrices must be same.
  1. TRUE
  2. FALSE
  3. Not necessarily
  4. None

NOTE: To multiply 2 matrices, number of columns of first matrix must be equal to number of rows of second matrix.