# Matrix addition using pointer and function?

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

void add(int *,int *,int *,int,int);

void main()

{

int r,c,r2,c2,i,j,*x,*y,*z;

clrscr();

printf("%47s\n","MATRIX ADDITION");

printf("%47s\n","---------------");

printf("\nEnter the row size of first matrix: ");

scanf("%d",&r);

printf("\nEnter the column size for the first matrix: ");

scanf("%d",&c);

printf("\nEnter the row size of second matrix: ");

scanf("%d",&r2);

printf("\nEnter the column size for the first matrix: ");

scanf("%d",&c2);

if(r!=r2c!=c2)

{

printf("\nMatrix addition impossible");

getch();

exit(0);

}

clrscr();

x=(int *)malloc(r*c*sizeof(int));

y=(int *)malloc(r*c*sizeof(int));

z=(int *)malloc(r*c*sizeof(int));

printf("\nEnter the elements of first matrix :\n");

for(i=0;i<r;i++)

{

printf("\nEnter elements of row %d\n",i+1);

for(j=0;j<c;j++)

{

printf("\nEnter x(%d,%d)",i+1,j+1);

scanf("%d",x+i*c+j);

}

}

clrscr();

printf("\nEnter the elements of second matrix :\n");

for(i=0;i<r;i++)

{

printf("\nEnter elements of row %d\n",i+1);

for(j=0;j<c;j++)

{

printf("\nEnter y(%d,%d)",i+1,j+1);

scanf("%d",y+i*c+j);

}

}

add(x,y,z,r,c);

/* Z is an output parameter:

Returning values through arguments */

clrscr();

printf("First Matrix is: \n\n");

for(i=0;i<r;i++)

{

for(j=0;j<c;j++)

printf("%d\t",*(x+i*c+j));

printf("\n\n");

}

printf("Second Matrix is: \n\n");

for(i=0;i<r;i++)

{

for(j=0;j<c;j++)

printf("%d\t",*(y+i*c+j));

printf("\n\n");

}

printf("Their sum is: \n\n");

for(i=0;i<r;i++)

{

for(j=0;j<c;j++)

printf("%d\t",*(z+i*c+j));

printf("\n\n");

}

free(x);

free(y);

free(z);

getch();

}

void add(int *x,int *y,int *z,int r,int c)

{

int i,j;

for(i=0;i<r;i++)

{

for(j=0;j<c;j++)

*(z+i*c+j)=*(x+i*c+j)+*(y+i*c+j);

}

}