C Program to Add Two Matrices:
During the Addition of Matrix in c programming, the number of rows and number of columns for both the matrices must be the same.
Before we start, if you want to learn about the Arrays as this program uses array, click the link below.
C Program for Matrix Addition
Firstly, declare array and integer to store the matrices. The program takes the user input for both rows and columns and then takes the elements for both matrices. Then by adding both the matrices (c[i][j] = a[i][j]+b[i][j];
), program display the result which is stored in c[][] (printf("%d ",c[i][j]);
)
Source Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | #include <stdio.h> int main() { int A[50][50], B[50][50], C[50][50]; int i, j, m, n; //User Inputs printf("Enter number of columns and rows for the matrix:\n"); scanf("%d%d", &m, &n); printf("Enter the elements for first matrix :\n"); for (i = 0; i < m; ++i) for (j = 0; j < n; ++j) scanf("%d", &A[i][j]); printf("Enter the elements for second matrix:\n"); for (i = 0; i < m; ++i) for (j = 0; j < n; ++j) scanf("%d", &B[i][j]); //Addition operation and displaying printf("Result of Matrix Addition\n"); for (i = 0; i < m; ++i) { for (j = 0; j < n; ++j) { C[i][j] = A[i][j] + B[i][j]; printf("%d ", C[i][j]); //displaying } printf(" \n"); } return 0; } |
The output of Matrix Addition in C program.
