Subtract two matrices using pointers
C Program to subtract two matrices using pointer
Program
#include<stdio.h>
#include<conio.h>
#define MAX 50
void print_matrix(int mat[MAX][MAX], int rows, int cols);
void input_matrix(int mat[MAX][MAX], int rows, int cols);
void main()
{
int mat1[MAX][MAX], mat2[MAX][MAX], sub[MAX][MAX];
int rows, cols;
int i, j;
printf("Enter the number of rows in the matrix\t:");
scanf("%d",&rows);
printf("Enter the number of columns in the matrix\t:");
scanf("%d",&cols);
printf("\nEnter elements in the first matrix\n");
input_matrix(mat1, rows, cols);
printf("\nEnter elements in the second matrix\n");
input_matrix(mat2, rows, cols);
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
*(*(sub + i) + j) = *(*(mat1 + i) + j) - *(*(mat2 + i) + j);
}
}
printf("\nFirst Matrix\n");
print_matrix(mat1, rows, cols);
printf("\nSecond Matrix\n");
print_matrix(mat2, rows, cols);
printf("\nSubtraction Matrix\n");
print_matrix(sub, rows, cols);
getch();
}
void input_matrix(int mat[MAX][MAX], int rows, int cols)
{
int i, j;
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
scanf("%d",(*(mat+i)+j));
}
}
}
void print_matrix(int mat[MAX][MAX], int rows, int cols)
{
int i, j;
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
printf("%3d ",*(*(mat+i)+j));
}
printf("\n");
}
}
Output
Enter the number of rows in the matrix :3
Enter the number of columns in the matrix :3
Enter elements in the first matrix
12
23
34
45
56
67
78
89
90
Enter elements in the second matrix
90
89
78
67
56
45
34
23
12
First Matrix
12 23 34
45 56 67
78 89 90
Second Matrix
90 89 78
67 56 45
34 23 12
Subtraction Matrix
-78 -66 -44
-22 0 22
44 66 78
44 66 78