img
Question:
Published on: 21 November, 2024

Write a C program to addition of two matrices.

Answer:

 

#include<stdio.h>
#include<conio.h>
main()
{
	int a[10][10],b[10][10],c[10][10],m,n,p,q,i,j;
	printf("\n Enter the dimension of the 1st matrix");
	scanf("%d %d",&m,&n);
	printf("\n Enter the dimension of the 2nd matrix");
	scanf("%d %d",&p,&q);
	if(m!=p||n!=q)
	 printf("\n Error in input, we can't add.Dimension must be equal.");
	else
	 {
	 	printf("\n Enter the elements of 1st matrix");
	 	for(i=0;i<m;i++)
	 	{
	 		for(j=0;j<n;j++)
	 	 	 scanf("%d",&a[i][j]);
	 	}
	 	printf("\n Enter the elements of 2nd matrix");
		for(i=0;i<p;i++)
		{
			for(j=0;j<q;j++)
			 scanf("%d",&b[i][j]);	
		} 
		for(i=0;i<m;i++)
		{
			for(j=0;j<n;j++)
			 c[i][j]=a[i][j]+b[i][j];
		}
		printf("\n The result matrix is :\n");
		for(i=0;i<m;i++)
		{
			for(j=0;j<n;j++)
			 printf("%d\t",c[i][j]);
			printf("\n"); 
		}
	 } 
	 getch();
}


Output:

Random questions