This blog is under construction

Monday 22 July 2013

C program to multiply two matrices using pointers

Write a C program to multiply two matrices using pointers.


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

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

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

        /* dyamically 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 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", (*(mat1 + i) + j));
                }
        }

        /* get the input for 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));
                }
        }
        /* multiply first and second matrix */
        for (i = 0; i < n; i++) {
                for (j = 0; j < n; j++) {
                        *(*(res + i) + j) = 0;
                        for (k = 0; k < n; k++) {
                                *(*(res + i) + j) = *(*(res + i) + j) +
                                        (*(*(mat1 + i) + k) * *(*(mat2 + k) + j));
                        }
                }
        }

        /* print the result */
        printf("\nResult After Multiplication:\n");
        for (i = 0; i < n; i++) {
                for (j = 0; j < n; j++) {
                        printf("%d ", *(*(res + 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
  1 2 3
  1 2 3
  Enter your input for matrix 2:
  1 1 1
  2 2 2
  3 3 3

  Result After Multiplication:
  14 14 14 
  14 14 14   
  14 14 14 


1 comment:

  1. this code of is not working on the length on 1,1,1,1.

    ReplyDelete