• Post author:
  • Reading time:2 mins read
  • Post category:C Programs

In this example, you will be able to add two matrices.

To add two matrices using c programming you must have some knowledge on:


Program to Add Two Matrices

The program for the addition of two 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

In the above programming example, the user is asked to enter the dimensions of both the matrices. Then the user is asked to enter the matrices.

In order to add two matrices, two for loops are used to iterate over each element of the matrix to add them. The sum is stored in result matrix.

After adding all elements the result matrix is printed onto the console.

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].