write a program to add subtract any two matrices in c

Solutions on MaxInterview for write a program to add subtract any two matrices in c by the best coders in the world

showing results for - "write a program to add subtract any two matrices in c"
Niklas
28 Jul 2019
1#include <stdio.h>
2#include <stdlib.h>
3
4void main ()
5{
6    int i, j, m, n;
7    char user_decision;
8    int matrix1[10][10],matrix2[10][10],sum[10][10],diff[10][10];
9
10    printf("Enter number of rows : ");
11    scanf("%d", &m);
12    printf("Enter number of columns : ");
13    scanf("%d", &n);
14
15    printf("\n");
16
17    for (i = 0; i < m; i++)
18    {
19        for (j = 0; j < n; j++)
20        {
21            printf("Enter element of matrix 1[%d][%d]: ", i, j);
22            scanf("%d", &matrix1[i][j]);
23        }
24    }
25
26    printf("\n");
27
28    for (i = 0; i < m; i++)
29    {
30        for (j = 0; j < n; j++)
31        {
32            printf("Enter elements of matrix 2[%d][%d]: ", i, j);
33            scanf("%d", &matrix2[i][j]);
34        }
35    }
36
37    printf("\n");
38
39    printf("type a if you want to add or type s if you want to subtract the matrix: ");
40    fflush(stdin);
41    scanf("%c",&user_decision);
42
43    printf("\n....Your resultant matrix is....\n\n");
44
45    if(user_decision=='a' || user_decision =='A')
46    {
47        for (i = 0; i < m; i++)
48        {
49            for (j = 0; j < n; j++)
50            {
51                sum[i][j] = matrix1[i][j] + matrix2[i][j];
52            }
53
54        }
55
56        for (i = 0; i < m; i++)
57        {
58            for (j = 0; j < n; j++)
59            {
60                printf("%d\t", sum[i][j]);
61            }
62            printf("\n");
63        }
64    }
65
66    else if(user_decision=='s' || user_decision =='S')
67    {
68        for (i = 0; i < m; i++)
69        {
70            for (j = 0; j < n; j++)
71            {
72                diff[i][j] = matrix1[i][j] - matrix2[i][j];
73            }
74
75        }
76
77        for (i = 0; i < m; i++)
78        {
79            for (j = 0; j < n; j++)
80            {
81                printf("%d\t", diff[i][j]);
82            }
83            printf("\n");
84        }
85    }
86
87    else
88        printf("Invalid selection");
89}
90