#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
#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,
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,
This example demonstrates how to add two 2x2 matrices and print the resulting matrix.
#include <stdio.h>
int main() {
int a[2][2] = {{1, 2}, {3, 4}};
int b[2][2] = {{5, 6}, {7, 8}};
int sum[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
sum[i][j] = a[i][j] + b[i][j];
}
}
printf("Sum of matrices:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%d ", sum[i][j]);
}
printf("\n");
}
return 0;
}
Output:
Sum of matrices:
6 8
10 12
---
This example allows users to input two 3x3 matrices and calculates their sum.
#include <stdio.h>
int main() {
int a[3][3], b[3][3], sum[3][3];
printf("Enter the elements of first 3x3 matrix:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
scanf("%d", &a[i][j]);
}
}
printf("Enter the elements of second 3x3 matrix:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
scanf("%d", &b[i][j]);
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
sum[i][j] = a[i][j] + b[i][j];
}
}
printf("Sum of matrices:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", sum[i][j]);
}
printf("\n");
}
return 0;
}
Output:
Enter the elements of first 3x3 matrix:
1 2 3
4 5 6
7 8 9
Enter the elements of second 3x3 matrix:
9 8 7
6 5 4
3 2 1
Sum of matrices:
10 10 10
10 10 10
10 10 10