Matrix Sum- Using Pointers
#include<stdio.h>
#include<stdlib.h>
int ** createMatrix(int,int);
void readMatrix(int **, int, int);
int findSum(int **, int, int);
int main() {
int m,n;
//printf("Enter Rows");
scanf("%d",&m);
//printf("Enter Columns");
scanf("%d",&n);
int **p = createMatrix(m,n);
readMatrix(p,m,n);
int sum = findSum(p,m,n);
printf("The sum of the elements in the matrix is %d\n",sum);
return 0;
}
int ** createMatrix(int m, int n) {
int i;
int **p = (int **) malloc(sizeof(int*)*m);
for(i=0;i<m;i++) {
*(p+i) = (int *) malloc(sizeof(int) * n);
}
return p;
}
void readMatrix(int **p, int m, int n) {
int i,j;
for(i=0;i<m;i++) {
for(j=0;j<n;j++) {
scanf("%d", (*(p+i)+j) );
}
}
}
int findSum(int **p, int m, int n) {
int i,j, sum=0;
for(i=0;i<m;i++) {
for(j=0;j<n;j++) {
sum+=*(*(p+i)+j);
}
}
return sum;
}
No comments:
Post a Comment