Program
Time Complexity: O(m*n) where m and n are the number of rows and columns in matrix.
Space Compexity: O(1)
m=max(r1,r2)
n=max(c1,c2)
#include <stdio.h> int main() { printf("****************************************************"); printf("\n****************************************************"); printf("\n** WAP to add two matrices or 2D arrays **"); printf("\n** Created by Sheetal Garg **"); printf("\n** Assistant Professor **"); printf("\n** Phone No:9467863365 **"); printf("\n****************************************************"); printf("\n****************************************************\n"); int r1, c1, r2, c2, i, j, a[5][5], b[5][5], c[5][5]; printf("Enter no. of rows and columns of first matrix\n"); scanf("%d%d", &r1, &c1); printf("Enter no. of rows and columns of second matrix\n"); scanf("%d%d", &r2, &c2); if (r1 == r2 && c1 == c2) { printf("enter elements of first matrix\n"); for (i = 0; i < r1; i++) for (j = 0; j < c1; j++) scanf("%d", &a[i][j]); printf("enter elements of second matrix\n"); for (i = 0; i < r2; i++) for (j = 0; j < c2; j++) scanf("%d", &b[i][j]); for (i = 0; i < r1; i++) for (j = 0; j < c1; j++) c[i][j] = a[i][j] + b[i][j]; printf("\nThe first matrix is\n"); for (i = 0; i < r1; i++) { for (j = 0; j < c1; j++) printf("%d\t", a[i][j]); printf("\n"); } printf("\nThe second matrix is\n"); for (i = 0; i < r2; i++) { for (j = 0; j < c2; j++) printf("%d\t", b[i][j]); printf("\n"); } printf("\nThe resultant matrix addition is\n"); for (i = 0; i < r1; i++) { for (j = 0; j < c1; j++) printf("%d\t", c[i][j]); printf("\n"); } } else printf("\nmatrices cant be added"); return 0; }
Output 1
**************************************************** **************************************************** ** WAP to add two matrices or 2D arrays ** ** Created by Sheetal Garg ** ** Assistant Professor ** ** Phone No:9467863365 ** **************************************************** **************************************************** Enter no. of rows and columns of first matrix 3 3 Enter no. of rows and columns of second matrix 3 3 enter elements of first matrix 1 2 3 2 3 4 3 4 5 enter elements of second matrix 2 3 1 1 1 2 2 1 1 The first matrix is 1 2 3 2 3 4 3 4 5 The second matrix is 2 3 1 1 1 2 2 1 1 The resultant matrix addition is 3 5 4 3 4 6 5 5 6
Output 2
**************************************************** **************************************************** ** WAP to add two matrices or 2D arrays ** ** Created by Sheetal Garg ** ** Assistant Professor ** ** Phone No:9467863365 ** **************************************************** **************************************************** Enter no. of rows and columns of first matrix 3 3 Enter no. of rows and columns of second matrix 3 2 matrices cant be added