C LAB‎ > ‎(Sem2) Data Structures‎ > ‎

Qx15. WAP to Add, Subtract, Multiply two 2D Arrays.

posted Mar 15, 2011, 1:41 AM by Neil Mathew   [ updated Mar 15, 2011, 1:45 AM ]

SOURCE CODE:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include<stdio.h>
 
void Matrix_Display(int a[][20],int n)
{
     int i,j;
     for(i=0; i<n; i++)
     {        
      for(j=0; j<n; j++)
       {
        printf(" %d",a[i][j]);   
       }
      printf("\n");
     }
 
}
 
int main()
{
    int n,i,j,k;
    int a[20][20];
    int b[20][20];
    int c[20][20];
    
    printf("\n Enter the dimensions of the 2 Square matrices: ");
    scanf("%d",&n);
    
    printf("\n Enter elements of Matrix A: ");
    for(i=0; i<n; i++)
    for(j=0; j<n; j++)
    scanf("%d",&a[i][j]);
    
    printf("\n Enter elements of Matrix B: ");
    for(i=0; i<n; i++)
    for(j=0; j<n; j++)
    scanf("%d",&b[i][j]);
    
    printf("\n Matrix A: \n");
    Matrix_Display(a,n);
           
    printf("\n\n Matrix B: \n");
    Matrix_Display(b,n);
    
    //Addition
    for(i=0; i<n; i++)
    for(j=0; j<n; j++)
    c[i][j]=a[i][j]+b[i][j];
    
    printf("\n\n Addition of A and B gives: \n");
    Matrix_Display(c,n);
    
     //Subtraction
    for(i=0; i<n; i++)
    for(j=0; j<n; j++)
    c[i][j]=a[i][j]-b[i][j];
    
    printf("\n\n Subtraction of A and B gives: \n");
    Matrix_Display(c,n);
    
    //Multiplication
    for(i=0; i<n; i++)
    for(j=0; j<n; j++)
    {
     c[i][j]=0;
     for(k=0; k<n; k++)
     c[i][j]+=a[i][k]*b[k][j];
    }
    
    printf("\n\n Multiplication of A and B gives: \n");
    Matrix_Display(c,n);
       
}
 

OUTPUT:

 Enter the dimensions of the 2 Square matrices: 2

 Enter elements of Matrix A: 1 2 3 4

 Enter elements of Matrix B: 4 3 2 1

 Matrix A:
 1 2
 3 4


 Matrix B:
 4 3
 2 1


 Addition of A and B gives:
 5 5
 5 5


 Subtraction of A and B gives:
 -3 -1
 1 3


 Multiplication of A and B gives:
 8 5
 20 13


Comments