sumitmehta
New Member
- Messages
- 215
- Reaction score
- 1
- Points
- 0
Hye Guys
I developed some useful and very basic C programs. I would like to share them with you. Here I am posting the first program. Pls let me know if I continue. These programs won't make much sense for experienced C programmers but they will be very useful for the beginners and intermediate programmers in C.
Pls. do rep me if you like my work.
Thanks.
Here is the first program on how to add two matrices using pointers.
I developed some useful and very basic C programs. I would like to share them with you. Here I am posting the first program. Pls let me know if I continue. These programs won't make much sense for experienced C programmers but they will be very useful for the beginners and intermediate programmers in C.
Pls. do rep me if you like my work.
Thanks.
Here is the first program on how to add two matrices using pointers.
Code:
include<stdio.h>
struct node {
int row;
int col;
int data;
struct node *next;
};
typedef struct node* NODE;
void add(NODE*,int,int,int);
NODE getMatrix(int,int);
NODE addMatrices(NODE*,NODE*);
void display(NODE*,int);
void add(NODE *n,int r,int c,int v) {
NODE temp=*n,t=*n;
NODE newN=(struct node *)malloc(sizeof(struct node));
newN->data=v;
newN->row=r;
newN->col=c;
newN->next=NULL;
if(temp==NULL)
temp=newN;
else {
while(t->next!=NULL)
t=t->next;
t->next=newN;
}
*n=temp;
}
NODE getMatrix(int r,int c) {
int i,j;
int data;
NODE m=NULL;
for(i=0;i<r;i++) {
for(j=0;j<c;j++) {
printf("\nEnter element for row %d & column %d : ",i+1,j+1);
scanf("%d",&data);
add(&m,i+1,j+1,data);
}
}
return m;
}
NODE addMatrices(NODE *m1,NODE *m2) {
NODE temp1=*m1;
NODE temp2=*m2;
NODE r=NULL;
int data;
while(temp1!=NULL) {
data=temp1->data + temp2->data;
add(&r,temp1->row,temp1->col,data);
temp1=temp1->next;
temp2=temp2->next;
}
return r;
}
void display(NODE *matrix,int c) {
NODE m=*matrix;
printf("\n");
while(m!=NULL) {
printf("%d\t",m->data);
if(m->col==c)
printf("\n");
m=m->next;
}
}
void main() {
int r,c;
NODE m1=NULL,m2=NULL,m3=NULL;
clrscr();
printf("Enter number of total rows for both matrices: ");
scanf("%d",&r);
printf("Enter number of total columns for noth matrices: ");
scanf("%d",&c);
printf("\nDetails for Matrix 1: ");
m1=getMatrix(r,c);
printf("\nDetails for Matrix 2: ");
m2=getMatrix(r,c);
m3=addMatrices(&m1,&m2);
printf("Matrix 1: ");
display(&m1,c);
printf("Matrix 2: ");
display(&m2,c);
printf("Resultant Matrix: ");
display(&m3,c);
getch();
}
Last edited by a moderator: