Matrix Addition in C

In this example, You will find program for matrix addition in C. 

When you try to add two matrices then consider two matrices when the number of rows and number of columns of both the matrix is equal. Matrices are of the same size. we do the addition of two 3*3 matrix in C.

Matrix Addition in C


#include<stdio.h>

int main(){
	
	int i,j,rows,cols;
		printf("Enter number of rows and columns:");
		scanf("%d\t%d",&rows,&cols);
		int a[rows][cols],b[rows][cols],c[rows][cols];
	printf("Enter Elements of First Matrix:");
	for(i=0;i<rows;i++)
	{
		for(j=0;j<cols;j++)
		scanf("%d",&a[i][j]);
	}
	printf("\nEnter Elements of Second Matrix:");
	for(i=0;i<rows;i++)
	{
		for(j=0;j<cols;j++)
		scanf("%d",&b[i][j]);
	}
	printf("First Matrix:\n");
	for(i=0;i<rows;i++)
	{
		for(j=0;j<cols;j++)
		printf("%d ",a[i][j]);
		printf("\n");
	}
	printf("Second Matrix:\n");
	for(i=0;i<rows;i++)
	{
		for(j=0;j<cols;j++)
		printf("%d ",b[i][j]);
		printf("\n");
	}
	for(i=0;i<rows;i++)
	{
		for(j=0;j<cols;j++)
		c[i][j]=a[i][j]+b[i][j];
	}
	printf("Adition Matrix:\n");
	for(i=0;i<rows;i++)
	{
		for(j=0;j<cols;j++)
		printf("%d ",c[i][j]);
		printf("\n");
	}
	printf("Subtraction Matrix:\n");
	for(i=0;i<rows;i++)
	{
		for(j=0;j<cols;j++)
		c[i][j]=a[i][j]-b[i][j];
	}
	for(i=0;i<rows;i++)
	{
		for(j=0;j<cols;j++)
		printf("%d ",c[i][j]);
		printf("\n");
	}
	return 0;
}

Output


Enter Elements of Second Matrix:
 8
 5
 4
 3
 10
 5
 9
 6
 3

 First Matrix:
 1 2 5
 4 3 7
 9 10 2

 Second Matrix:
 8 5 4
 3 10 5
 9 6 3

 Adition Matrix:
 9 7 9 
 7 13 12
 18 16 5
In the Above article, we learn about matrix addition in C and how it works for 3*3 matrix multiplication. In upcoming tutorials, we discuss subtraction, multiplication of two matrix, transpose with algorithms in detail. If you learn from the above example then try to solve these which we see in upcoming examples and comment your solution below.

Happy Coding 😊

If you have any doubts, Please let me know

Previous Post Next Post

Contact Form