C : Program to accept two matrices and add it
2 min readOct 17, 2023
Program :
//c program to accept two matrices and add two matrices
#include<stdio.h>
int main()
{
printf("Program of addition of two matrices :\n\n");
int rows, columns;
//Get output from user for number rows and columns
printf("Enter the number of rows : ");
scanf("%d", &rows);
printf("Enter the number of columns : ");
scanf("%d", &columns);
int mat1[rows][columns],
mat2[rows][columns],
result[rows][columns];
//Get output from user for to get elements in first matrix
printf("\nEnter the elements at first matrix : \n");
for(int i=0; i<rows; i++)
{
for(int j=0; j<columns; j++)
{
printf("Enter the number at %d row and %d column :", i+1, j+1 );
scanf("%d", &mat1[i][j]);
}
}
//Get output from user for to get elements in second matrix
printf("\nEnter the elements at second matix :\n");
for(int i=0; i<rows; i++)
{
for(int j=0; j<columns; j++)
{
printf("Enter the number at %d row and %d column :", i+1, j+1 );
scanf("%d", &mat2[i][j]);
}
}
//Printing of first matix
printf("\nFirst matrix : \n");
for(int i=0; i<rows; i++)
{
for(int j=0; j<columns; j++)
{
printf("%d ", mat1[i][j]);
}
printf("\n");
}
//Printing of second matix
printf("\nSecond matrix : \n");
for(int i=0; i<rows; i++)
{
for(int j=0; j<columns; j++)
{
printf("%d ", mat2[i][j]);
}
printf("\n");
}
//Result of the matrix
for(int i=0; i<rows; i++)
{
for(int j=0; j<columns; j++)
{
result[i][j] = mat1[i][j] + mat2[i][j];//for subtraction use "-"
}
}
//Pritnting result of the two matrix
printf("\nResultant matrix : \n");
for(int i=0; i<rows; i++)
{
for(int j=0; j<columns; j++)
{
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0;
}
Output :
Note : For subtracting use “-”.