Sum of two matrix

To find the sum of two matrices, here we used two dimensional arrays to define a matrix and then using loops the addtion of elements is done.

Inputs to the script

User has to enter matrix size and elements, or it can be fixed while declaring

Processing

By looping through elements the multiplication is done.

Output of the script

We will get sum of the matrix in matrix form.

Sum of 2x2 matrix

#include <stdio.h>
int main(void){
int i,j;
int num1[2][2]={
                {1,2},
                {3,4}
                };

int num2[2][2]={
                {5,6},
                {7,8}                
                };
int sum[2][2];
////adding ///
for(i=0;i<2;i++){

for(j=0;j<2;j++){
sum[i][j]=num1[i][j] + num2[i][j];
}
}
/////displaying////
for(i=0;i<2;i++){

for(j=0;j<2;j++){
printf(" %d  ", sum[i][j]);
}
printf("\n");
}
///
return 0;
}
Output
 6   8
 10   12

3x3 Matrix Sum

#include <stdio.h>
int main(void){
int i=3,j=3;
int num_final[i][j];
int num1[3][3]={{1,2,3},
                {4,5,6},
	        {7,8,9}};
int num2[3][3]={{10,20,30},
                {40,50,60},
	        {70,80,90}};

for(i=0;i<3;i++){
 for(j=0;j<3;j++){
     num_final[i][j]=num1[i][j]+num2[i][j];
}
}
///// addition is over , now display the result //

for(i=0;i<3;i++){
    for(j=0;j<3;j++){
        printf("%d,",num_final[i][j]);
    }
printf("\n");
}
Outut is here
11,22,33,
44,55,66,
77,88,99,

Subtraction of matrix

In the above code we will replace the addition with subtraction.
Check this line
num_final[i][j]=num1[i][j]+num2[i][j];
Change this line like this
num_final[i][j]=num2[i][j]-num1[i][j];
Your output is here
9,18,27,
36,45,54,
63,72,81,
Multiplication of Matrix Two dimensional Array in C

Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here




    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2021 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer