Write a C program to add two matrices.
int main () {
int mat1[100][100], mat2[100][100], row, col, i, j, out[100][100];
/* get the number of rows and columns (n X n) */
printf("Rows and Columns:");
scanf("%d%d", &row, &col);
/* input first matrix */
printf("Matrix1 Inputs:\n");
for (i = 0; i < row; i++)
for (j = 0; j < col; j++)
scanf("%d", &mat1[i][j]);
/* input second matrix */
printf("Matrix2 Inputs:\n");
for (i = 0; i < row; i++)
for (j = 0; j < col; j++)
scanf("%d", &mat2[i][j]);
/* Add first and second matrix */
for (i = 0; i < row; i++)
for (j = 0; j < col; j++)
out[i][j] = mat1[i][j] + mat2[i][j];
/* print the result */
printf("Output:\n");
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++)
printf("%3d", out[i][j]);
printf("\n");
}
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Rows and Columns:2 2
Matrix1 Inputs:
10 20
30 4
Matrix2 Inputs:
50 60
70 80
Output:
60 80
100 84
Rows and Columns:2 2
Matrix1 Inputs:
10 20
30 4
Matrix2 Inputs:
50 60
70 80
Output:
60 80
100 84
No comments:
Post a Comment