geochareas

Array Multi

Sep 9th, 2020
535
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2.  
  3.  
  4. void getMatrixElements(int matrix[][10], int row, int column) {
  5.  
  6.    printf("\nEnter elements: \n");
  7.  
  8.    for (int i = 0; i < row; ++i) {
  9.       for (int j = 0; j < column; ++j) {
  10.          printf("Enter a%d%d: ", i + 1, j + 1);
  11.          scanf("%d", &matrix[i][j]);
  12.       }
  13.    }
  14. }
  15.  
  16. // function to multiply two matrices
  17. void multiplyMatrices(int first[][10],
  18.                       int second[][10],
  19.                       int result[][10],
  20.                       int r1, int c1, int r2, int c2) {
  21.  
  22.    // Initializing elements of matrix mult to 0.
  23.    for (int i = 0; i < r1; ++i) {
  24.       for (int j = 0; j < c2; ++j) {
  25.          result[i][j] = 0;
  26.       }
  27.    }
  28.  
  29.    // Multiplying first and second matrices and storing it in result
  30.    for (int i = 0; i < r1; ++i) {
  31.       for (int j = 0; j < c2; ++j) {
  32.          for (int k = 0; k < c1; ++k) {
  33.             result[i][j] += first[i][k] * second[k][j];
  34.          }
  35.       }
  36.    }
  37. }
  38.  
  39. // function to display the matrix
  40. void display(int result[][10], int row, int column) {
  41.  
  42.    printf("\nOutput Matrix:\n");
  43.    for (int i = 0; i < row; ++i) {
  44.       for (int j = 0; j < column; ++j) {
  45.          printf("%d  ", result[i][j]);
  46.          if (j == column - 1)
  47.             printf("\n");
  48.       }
  49.    }
  50. }
  51.  
  52. int main() {
  53.    int first[10][10], second[10][10], result[10][10], r1, c1, r2, c2;
  54.    printf("Enter rows and column for the first matrix: ");
  55.    scanf("%d %d", &r1, &c1);
  56.    printf("Enter rows and column for the second matrix: ");
  57.    scanf("%d %d", &r2, &c2);
  58.  
  59.    // Taking input until
  60.    // 1st matrix columns is not equal to 2nd matrix row
  61.    while (c1 != r2) {
  62.       printf("Error! Enter rows and columns again.\n");
  63.       printf("Enter rows and columns for the first matrix: ");
  64.       scanf("%d%d", &r1, &c1);
  65.       printf("Enter rows and columns for the second matrix: ");
  66.       scanf("%d%d", &r2, &c2);
  67.    }
  68.  
  69.    // get elements of the first matrix
  70.    getMatrixElements(first, r1, c1);
  71.  
  72.    // get elements of the second matrix
  73.    getMatrixElements(second, r2, c2);
  74.  
  75.    // multiply two matrices.
  76.    multiplyMatrices(first, second, result, r1, c1, r2, c2);
  77.  
  78.    // display the result
  79.    display(result, r1, c2);
  80.  
  81.    return 0;
  82. }
RAW Paste Data