This blog is under construction

Sunday 21 July 2013

C program to add two matrices using pointers

Write a C program to add two matrices using dynamic memory allocation.


  #include <stdio.h>
  #include <stdlib.h>

  int main() {
        int **mat1, **mat2, **res, i, j, n;

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

        /* dynamically allocate memory to store elements */
        mat1 = (int **) malloc(sizeof(int *) * n);
        mat2 = (int **) malloc(sizeof(int *) * n);
        res  = (int **) malloc(sizeof(int *) * n);

        for (i = 0; i < n; i++) {
                *(mat1 + i) = (int *) malloc(sizeof(int) * n);
                *(mat2 + i) = (int *) malloc(sizeof(int) * n);
                *(res  + i) = (int *) malloc(sizeof(int) * n);
        }


        /* get the input for matrix 1 */
        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));
                }
        }

        /* get the input for matrix 2 */
        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));
                }
        }

        /* calculate the sum of given two matrices */
        for (i = 0; i < n; i++) {
                for (j = 0; j < n; j++) {
                        *(*(res + i) + j) =
                                *(*(mat1 + i) + j) + *(*(mat2 + i) + j);
                }
        }

        /* print the resultant matrix */
        printf("Result For The Addition Of Given Two Matrices:\n");
        for (i = 0; i < n; i++) {
                for (j = 0; j < n; j++) {
                        printf("%d ", *(*(res + i)));
                }
                printf("\n");
        }

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the order of matrices: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
  Result For The Addition Of Given Two Matrices:
  10 10 10 
  10 10 10 
  10 10 10 


2 comments: