Matrices are integral components of various computational algorithms and performing operations on matrices is a fundamental aspect of programming. In this article, we are going to see how can we perform matrix addition in C.
Table of Contents
Matrix Addition
Matrix addition is a straightforward operation where each element of the resulting matrix is obtained by adding the corresponding element of the input matrices. For Example- if we have two matrices A and B of dimension mxn, the resultant Sum(a+b) will be the mxn matrix, and each element of Sum[i][j] will be the sum of A[i][j] and B[i][j].
C Program for Matrix Addition
Let’s write a C program that adds to matrices. In this example we will use nested loops to iiterate through each elemnets of matrices, performing the addition operation and stroring the result in a new matrix.
Note- If you don’t know how to take matrix input and print the matrix refers this tutorial- Matrix Input and Output in C
#include <stdio.h>
// Function to add two matrices
void addMatrices(int row, int column, int A[row][column], int B[row][column], int C[row][column])
{
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
C[i][j] = A[i][j] + B[i][j];
}
}
}
void main()
{
int row, column;
printf("Enter the number of rows ");
scanf("%d", &row);
printf("Enter the number of column ");
scanf("%d", &column);
int matrixA[row][column], matrixB[row][column], sum[row][column];
printf("Enter the element of first Matrices\n");
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
printf("Enter the element at position {%d,%d}", i, j);
scanf("%d", &matrixA[i][j]);
}
}
printf("Enter the element of second Matrices\n");
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
printf("Enter the element at position {%d,%d}", i, j);
scanf("%d", &matrixB[i][j]);
}
}
addMatrices(row, column, matrixA, matrixB, sum);
printf("resultant matrix after addition\n ");
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
printf("%d\t", sum[i][j]);
}
printf("\n");
}
}
Output
How Above Code Works?
- The
main
function is the entry point of an above C program. - We declare two variables row and column to store the dimensions of the matrices.
- Program asks users to enter the velue of row and column.
- Three matrices are declared-matrixA, matrixB, and sum, Each with dimensions specified by the user.
- Users then entered the element of both matrices matrix and matrix by using a nested loop.
- Function addMatrices is called with the dimension of the matrices and the matrices themselves.
- Inside the function, a nested loop iterates through each element of matrices performs the addition of corresponding elements, and stores the result in the sum matrix.
- At the end, the program prints the resultant matrix after the addition.
Happy Coding
2 thoughts on “Matrix Addition in C”