Home

A program to add and subtract two matrices and print resultant matrices

C Programming Language 063

The following code shows how to write a program to add and subtract two matrices and print resultant matrices.

Program

#include <stdio.h>

void main()
{
    int a[10][10], b[10][10], c[10][10], m, n, i, j;
    printf("Enter order m,n [m x n]: ");
    scanf("%d %d", &m, &n);

    printf("Enter values of matrix a[%d x %d]\n", m, n);
    for (i = 0; i < m; i++)
    {
        for (j = 0; j < n; j++)
        {
            scanf("%d", &a[i][j]);
        }
    }

    printf("Enter values of matrix b[%d x %d]\n", m, n);
    for (i = 0; i < m; i++)
    {
        for (j = 0; j < n; j++)
        {
            scanf("%d", &b[i][j]);
        }
    }

    printf("After addition:\n");
    for (i = 0; i < m; i++)
    {
        for (j = 0; j < n; j++)
        {
            printf("%d\t", a[i][j] + b[i][j]);
        }
        printf("\n");
    }

    printf("After subtraction:\n");
    for (i = 0; i < m; i++)
    {
        for (j = 0; j < n; j++)
        {
            c[i][j] = a[i][j] - b[i][j];
            printf("%d\t", c[i][j]);
        }
        printf("\n");
    }

    printf("\n");
}

Result

Enter order m,n [m x n]: 2 2
Enter values of matrix a[2 x 2]
2 1
3 4
Enter values of matrix b[2 x 2]
2 3
1 0
After addition:
4       4
4       4
After subtraction:
0       -2
2       4


Last Updated on

Next Post: GraphProtocol: TS2322 null assignment in Subgraph →

Comments