Matrix Addition

Matrix is 2D array in computer science. Take user input for row and colum. Allocate two 2D dynamic array A and B, first allocate pointes for row elemnets and then allocate columns elements and assign each column pointers to row list. Now populate elements for matrix A with user input. Then do the same for matrix B. Now take element[0,0] from A and B and add them. Repeat the same for rest of all positions individually. Thus the resultant matrix is formed.

Source Code

#include <stdio.h>
#include <malloc.h>
int main(int argc, char* argv[])
{
  int rows = 0;
  int cols = 0;
  int **matrix_a;
  int **matrix_b;
  int r, c;
  printf ("== Matrix Addition Demo ==\n");
  printf ("Matrix has rows : ");
  scanf ("%d", &rows);
  printf ("Matrix has columns : ");
  scanf ("%d", &cols);
  matrix_a = (int **) malloc (sizeof(int **)*rows);
  matrix_b = (int **) malloc (sizeof(int **)*rows);

  for (= 0; r < rows; r++) {
    matrix_a[r] = (int *) malloc(sizeof(int)*cols);
  }
  for (= 0; r < rows; r++) {
    matrix_b[r] = (int *) malloc(sizeof(int)*cols);
  }

  printf ("\nMatrix A\n");
  for (= 0; r < rows; r++) {
    for (= 0; c < cols; c++) {
      printf ("Element [%d][%d] : ", r, c);
      scanf ("%d", &matrix_a[r][c]);
    }
  }

  printf ("\nMatrix B\n");
  for (= 0; r < rows; r++) {
    for (= 0; c < cols; c++) {
      printf ("Element [%d][%d] : ", r, c);
      scanf ("%d", &matrix_b[r][c]);
    }
  }
  printf ("\nMatrix A\n");
  for (= 0; r < rows; r++) {
    printf ("| ");
    for (= 0; c < cols; c++) {
      printf ("%.2d ", matrix_a[r][c]);
    }
    printf (" |\n");
  }
  printf ("\nMatrix B\n");
  for (= 0; r < rows; r++) {
    printf ("| ");
    for (= 0; c < cols; c++) {
      printf ("%.2d ", matrix_b[r][c]);
    }
    printf(" |\n");
  }
  printf ("\nMatrix A + B\n");
  for (= 0; r < rows; r++) {
    printf ("| ");
    for (= 0; c < cols; c++) {
      printf ("%.2d ", (matrix_b[r][c] + matrix_b[r][c]));
    }
    printf (" |\n");
  }
  return 0;
}

Output

== Matrix Addition Demo ==
Matrix has rows : 4
Matrix has columns : 3
Matrix A
Element [0][0] : 1
Element [0][1] : 2
Element [0][2] : 3
Element [1][0] : 4
Element [1][1] : 5
Element [1][2] : 6
Element [2][0] : 7
Element [2][1] : 8
Element [2][2] : 9
Element [3][0] : 10
Element [3][1] : 11
Element [3][2] : 12
Matrix B
Element [0][0] : 13
Element [0][1] : 14
Element [0][2] : 15
Element [1][0] : 16
Element [1][1] : 17
Element [1][2] : 18
Element [2][0] : 19
Element [2][1] : 20
Element [2][2] : 21
Element [3][0] : 22
Element [3][1] : 23
Element [3][2] : 24

Matrix A
| 01 02 03 |
| 04 05 06 |
| 07 08 09 |
| 10 11 12 |

Matrix B
| 13 14 15 |
| 16 17 18 |
| 19 20 21 |
| 22 23 24 |

Matrix A + B
| 26 28 30 |
| 32 34 36 |
| 38 40 42 |
| 44 46 48 |

About our authors: Team EQA

You have viewed 1 page out of 248. Your C learning is 0.00% complete. Login to check your learning progress.

Learn on Youtube

#