- 2070 Asar · 6 marks
Add two matrices
Short answer
Two matrices of same order are added element-wise: s[i][j] = a[i][j] + b[i][j]. The program reads dimensions and elements, computes sum in nested loops, and displays the sum matrix. Ensure matching rows and columns before addition.
Write a C program to read two matrices from user, add them and display the result in matrix form.
Two matrices can be added only if they have the same order (rows and columns). The sum matrix S has s[i][j] = a[i][j] + b[i][j]. Nested loops read, add and print the matrices.
#include <stdio.h>
int main(void)
{
int a[10][10], b[10][10], s[10][10], r, c, i, j;
printf("Enter rows and columns: ");
scanf("%d %d", &r, &c);
printf("Enter first matrix:\n");
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
scanf("%d", &a[i][j]);
printf("Enter second matrix:\n");
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
scanf("%d", &b[i][j]);
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
s[i][j] = a[i][j] + b[i][j];
printf("Sum of the matrices:\n");
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++)
printf("%5d", s[i][j]);
printf("\n");
}
return 0;
}
Sample run
Input: 2 3 1 2 3 4 5 6 6 5 4 3 2 1
Enter rows and columns: Enter first matrix:
Enter second matrix:
Sum of the matrices:
7 7 7
7 7 7
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Add and subtract matrices in FORTRAN · Computer Programming, chapter 11
- Sum of two matrices in FORTRAN · Computer Programming, chapter 11
- Array overflow/underflow; add two arrays · Computer Programming, chapter 7
- Read records until end; show nth record · Computer Programming, chapter 10 · asked 2×
- Significance of arrays; multiply 3×3 matrices · Computer Programming, chapter 7
- Transpose m×n matrix in FORTRAN · Computer Programming, chapter 11
- Protected specifier; student/test/result program · Object Oriented Programming, chapter 6
- Add objects of two different classes · Object Oriented Programming, chapter 4 · asked 2×
- Time class: add two objects · Object Oriented Programming, chapter 1
- 8085 ALP: add two tables, sum and carry · Microprocessor, chapter 2