Write a program that performs the addition of two matrices A and B of the same dimensions R and C.
The result of the addition will be stored in a third matrix SUM which will then be displayed.
\(\begin{pmatrix} a & b & c & d \\e & f & g & h \\ i & j & k & l \end{pmatrix} + \begin{pmatrix} a' & b' & c' & d' \\e' & f' & g' & h' \\ i' & j' & k' & l' \end{pmatrix} = \begin{pmatrix} a+a' & b+b' & c+c' & d+d' \\e+e' & f+f' & g+g' & h+h' \\ i+i' & j+j' & k+k' & l+l' \end{pmatrix}\)
Difficulty level
Video recording
This exercise is mostly suitable for students
#include <stdio.h>
#include <conio.h>
#define SIZE 50
void main()
{
int A[SIZE][SIZE];
int B[SIZE][SIZE];
int SUM[SIZE][SIZE];
int R, C; /* dimensions */
int I, J;
do {
printf("Number of rows (max.%d) : ", SIZE);
scanf("%d", &R);
} while (R <= 0 || R > SIZE);
do {
printf("Number of columns (max.%d) : ", SIZE);
scanf("%d", &C);
} while (C <= 0 || C > SIZE);
printf("*** Matrix A ***\n");
for (I = 0; I<R; I++)
for (J = 0; J<C; J++)
{
printf("A[%d][%d] : ", I, J);
scanf("%d", &A[I][J]);
}
printf("*** Matrix B ***\n");
for (I = 0; I<R; I++)
for (J = 0; J<C; J++)
{
printf("B[%d][%d] : ", I, J);
scanf("%d", &B[I][J]);
}
printf("Matrix A :\n");
for (I = 0; I<R; I++)
{
for (J = 0; J<C; J++)
printf("%6d", A[I][J]);
printf("\n");
}
printf("Matrix B :\n");
for (I = 0; I<R; I++)
{
for (J = 0; J<C; J++)
printf("%6d", B[I][J]);
printf("\n");
}
for (I = 0; I<R; I++)
for (J = 0; J<C; J++)
SUM[I][J] = A[I][J] + B[I][J];
printf("Resultant matrix :\n");
for (I = 0; I<R; I++)
{
for (J = 0; J<C; J++)
printf("%6d", SUM[I][J]);
printf("\n");
}
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Check whether a given binary tree is a Max heap