What is Matrix addition in c?

Matrix addition in c can be done using two nested for-loops iterating through each elements in both matrix. See below program and explanation.


Program for addition of matrix in c

//C program to perform addition of two matrix.
#include<stdio.h>
int main(int argc, char const *argv[])
{
	int a,b;
	printf("\n\n\tEnter number and rows of matrices:\n\t");
	scanf("%d%d",&a,&b);
	int a_matrix[a][b],b_matrix[a][b],result[a][b];
	printf("\n\tEnter matrix A\n\t");
	for( int i=0 ; i<a; i++ )
	{
		for( int j=0 ; j<b ; j++ )
		{
			scanf("%d",&a_matrix[i][j]);
		}
	}
	printf("\n\tEnter matrix B\n\t");
	for( int i=0 ; i<a; i++ )
	{
		for( int j=0 ; j<b ; j++ )
		{
			scanf("%d",&b_matrix[i][j]);
		}
	}
	printf("\n\tAdding matrices A and B\n\t");
	for( int i=0 ; i<a; i++ )
	{
		for( int j=0 ; j<b ; j++ )
		{
			result[i][j]=a_matrix[i][j]+b_matrix[i][j];
		}
	}
	printf("\n\tResultant matrix is:\n\t");
	for( int i=0 ; i<a; i++ )
	{
		printf("\n\t");
		for( int j=0 ; j<b ; j++ )
		{
			printf("%d ",result[i][j]);
		}
	}
	printf("\n\n\n");
	return 0;
}

Explanation

First we take both matrices as two-dimensional array.

Then we use nested for loop to iterate through each elements and then add elements of the matrix and store it in result matrix.

Finally print the resultant matrix.

Output

	Enter rows and columns of matrices:
	2 2

	Enter matrix A
	1 2 3 4

	Enter matrix B
	1 2 3 4

	Adding matrices A and B
	
	Resultant matrix is:
	
	2 4 
	6 8 
Example program for Matrix addition in c output 1
	Enter rows and columns of matrices:
	3 3

	Enter matrix A
	1 2 3 4 5 6 7 8 9 

	Enter matrix B
	1 2 3 4 5 6 7 8 9

	Adding matrices A and B
	
	Resultant matrix is:
	
	2 4 6 
	8 10 12 
	14 16 18 
Example program for Matrix addition in c output 2

People also ask

How to add two matrix?

Add the elements of 1st matrix[i][j] with 2nd matrix[i][j].

People also read