This blog is under construction

Wednesday, 24 July 2013

C program to add two matrices without using third matrix

Write a C program to add two matrices without using third matrix.


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

  int main() {
        int mat1[MAXROW][MAXCOL], mat2[MAXROW][MAXCOL];
        int 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 matrix 1 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", &mat1[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", &mat2[i][j]);
                }
        }

        /* add 1st & 2nd matrix and store the o/p in 1st matrix */
        for (i = 0; i < n; i++) {
                for (j = 0; j < n; j++) {
                        mat1[i][j] = mat1[i][j] + mat2[i][j];
                }
        }

        /* print the resultant matrix */
        printf("Sum of given two matrices:\n");
        for (i = 0; i < n; i++) {
                for (j = 0; j < n; j++) {
                        printf("%d ", mat1[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:
  1 2 3
  4 5 6
  7 8 9
  Enter your input for matrix 2:
  9 8 7
  6 5 4
  3 2 1
  Sum of given two matrices:
  10 10 10 
  10 10 10 
  10 10 10 


No comments:

Post a Comment