Answers for "Write a program to obtain multiplication of a 4 x 4 matrix. with comments"

0

Write a program to obtain multiplication of a 4 x 4 matrix. with comments

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

int main() {
  int A[10][10], B[10][10], C[10][10];
  unsigned short m, p, q, n, i, j, k;

  printf("Rows (Matrix A): ");
  scanf("%hu", &m);

  printf("Columns (Matrix A): ");
  scanf("%hu", &p);

  printf("Rows (Matrix B): ");
  scanf("%hu", &q);

  if(p != q) {
  	printf("THE TWO MATRICES ARE NOT CONFORMABLE.\n");
  	exit(0);
  }

  printf("Columns (Matrix B): ");
  scanf("%hu", &n);

  // ELEMENTS OF MATRIX A

  for(i=0; i < m; i++) {
    for(j=0; j < p; j++) {
      printf("A[%hu,%hu]: ", i, j);
      scanf("%d", &A[i][j]);
    }
  }

  // ELEMENTS OF MATRIX B

  for(j=0; j < q; j++) {
    for(k=0; k < n; k++) {
      printf("B[%hu,%hu]: ", j, k);
      scanf("%d", &B[j][k]);
    }
  }

  // DISPLAY MATRIX A

  printf("Matrix A\n");

  for(i = 0; i < m; i++) {
    for(j = 0; j < p; j++) {
      printf("%d ", A[i][j]);
    }
    printf("\n");
  }

  // DISPLAY MATRIX B

  printf("Matrix B\n");

  for(j = 0; j < q; j++) {
    for(k = 0; k < n; k++) {
      printf("%d ", B[j][k]);
    }
    printf("\n");
  }

  // MULTIPLICATION

  for(i=0; i < m; i++) {
    for(j=0; j < n; j++) {
      C[i][j] = 0;
      for(k=0; k < p; k++) { // k < q WILL ALSO WORK
        C[i][j] += A[i][k]*B[k][j];
      }
    }
  }

  // DISPLAY MATRIX AB

  printf("Product Matrix AB\n");

  for(i = 0; i < m; i++) {
    for(k = 0; k < n; k++) {
      printf("%d ", C[i][k]);
    }
    printf("\n");
  }

  return 0;
}
Posted by: Guest on August-26-2021

Code answers related to "Write a program to obtain multiplication of a 4 x 4 matrix. with comments"

Browse Popular Code Answers by Language