Matrix Addition using C
#include<stdio.h>
#include<stdlib.h>
int ** dynamicMemAllocation(int m, int n);
void readMatrix(int **mat, int m, int n);
void addMatrix(int **mat1, int **mat2, int **res, int m, int n);
void printMatrix(int **mat, int m, int n);
int main()
{
int m, n, i;
int **mat1, **mat2, **res;
printf("Enter order of matrices: ");
scanf("%d %d", &m, &n);
mat1 = dynamicMemAllocation(m, n);
mat2 = dynamicMemAllocation(m, n);
res = dynamicMemAllocation(m, n);
readMatrix(mat1, m, n);
readMatrix(mat2, m, n);
addMatrix(mat1, mat2, res, m, n);
printMatrix(res, m, n);
return 0;
}
int ** dynamicMemAllocation(int m, int n)
{
int **mat;
int i;
mat = (int **)malloc(m * sizeof(int *));
for(i = 0; i < m; i++)
*(mat+i) = (int *)malloc(n * sizeof(int));
return mat;
}
void readMatrix(int **mat, int m, int n)
{
int i, j;
printf("Enter elements of matrix:\n");
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
{
scanf("%d", (*(mat+i)+j));
}
}
}
void addMatrix(int **mat1, int **mat2, int **res, int m, int n)
{
int i, j;
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
{
res[i][j] = mat1[i][j] + mat2[i][j];
}
}
}
void printMatrix(int **mat, int m, int n)
{
int i, j;
printf("The resultant matrix is : \n");
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
{
printf("%d ", mat[i][j]);
}
printf("\n");
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.