This blog is under construction

Wednesday 24 July 2013

C program to subtract two matrices

Write a C program to subtract two matrices.


  #include <stdio.h>
  #define MAXROW 10
  #define MAXCOL 10

  int main() {
        int matrix1[MAXROW][MAXCOL], matrix2[MAXROW][MAXCOL];
        int result[MAXROW][MAXCOL], i, j, n;

        /* get the order of the matrix from the user */
        printf("Enter the order of the matrix:");
        scanf("%d", &n);

        /* Boundary Check */
        if (n > MAXROW || n < 0) {
                printf("Boundary Level Exceeded!!\n");
                return 0;
        }

        /* input first matrix from the user */
        printf("Enter your input for matrix 1:\n");
        for (i = 0; i < n; i++) {
                for (j = 0; j < n; j++) {
                        scanf("%d", &matrix1[i][j]);
                }
        }

        /* input second matrix from the user */
        printf("Enter your input for matrix 2:\n");
        for (i = 0; i < n; i++) {
                for (j = 0; j < n; j++) {
                        scanf("%d", &matrix2[i][j]);
                }
        }

        /* add 1st & 2nd matrixrix and store the o/p in 1st matrixrix */
        for (i = 0; i < n; i++) {
                for (j = 0; j < n; j++) {
                        result[i][j] = matrix1[i][j] - matrix2[i][j];
                }
        }

        /* print the resultant matrixrix */
        printf("Difference b/w two given matrices:\n");
        for (i = 0; i < n; i++) {
                for (j = 0; j < n; j++) {
                        printf("%d ", result[i][j]);
                }
                printf("\n");
        }

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the order of the matrix:3
  Enter your input for matrix 1:
  2  3  4 
  5  6  7
  8  9  10
  Enter your input for matrix 2:
  1  1  1
  1  1  1
  1  1  1
  Difference b/w two given matrices:
  1  2  3 
  4  5  6 
  7  8  9 


No comments:

Post a Comment