Write a C program to find the sum of the elements in the matrix.
Input Format:
The input consists of (m*n+2) integers.
The first integer corresponds to m, the number of rows in the matrix and the second integer corresponds to n, the number of columns in the matrix.
The remaining integers correspond to the elements in the matrix. The elements are read in row-wise order, the first row first, then second row and so on. Assume that the maximum value of m and n is 10.
Output Format:
Refer sample output for details.
Sample Input and Output1:
Enter the number of rows in the matrix
3
Enter the number of columns in the matrix
2
Enter the elements in the matrix
4 5
6 9
0 3
The sum of the elements in the matrix is 27
Program Code:
#include<stdio.h>
#include<malloc.h>
int** create(int m, int n)
{
int **a, i;
a= (int **)malloc(m*sizeof(int *));
for(i=0; i<m; i++)
{
*(a+i) = (int *)malloc(n*sizeof(int ));
}
return a;
}
void read(int **a, int m, int n)
{
int i, j;
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
scanf("%d", (*(a+i)+j));
}
}
}
int findSum(int **a, int m, int n)
{
int i, j;
int sum=0;
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
sum = sum + *(*(a+i)+j);
}
}
return sum;
}
int main()
{
int **a, m, n;
printf("Enter the number of rows in the matrix\n");
scanf("%d",&m);
printf("Enter the number of columns in the matrix\n");
scanf("%d",&n);
printf("Enter the elements in the matrix\n");
a = create(m,n);
read(a,m,n);
printf("The sum of the elements in the matrix is %d", findSum(a,m,n));
return 0;
}
Input Format:
The input consists of (m*n+2) integers.
The first integer corresponds to m, the number of rows in the matrix and the second integer corresponds to n, the number of columns in the matrix.
The remaining integers correspond to the elements in the matrix. The elements are read in row-wise order, the first row first, then second row and so on. Assume that the maximum value of m and n is 10.
Output Format:
Refer sample output for details.
Sample Input and Output1:
Enter the number of rows in the matrix
3
Enter the number of columns in the matrix
2
Enter the elements in the matrix
4 5
6 9
0 3
The sum of the elements in the matrix is 27
Program Code:
#include<stdio.h>
#include<malloc.h>
int** create(int m, int n)
{
int **a, i;
a= (int **)malloc(m*sizeof(int *));
for(i=0; i<m; i++)
{
*(a+i) = (int *)malloc(n*sizeof(int ));
}
return a;
}
void read(int **a, int m, int n)
{
int i, j;
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
scanf("%d", (*(a+i)+j));
}
}
}
int findSum(int **a, int m, int n)
{
int i, j;
int sum=0;
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
sum = sum + *(*(a+i)+j);
}
}
return sum;
}
int main()
{
int **a, m, n;
printf("Enter the number of rows in the matrix\n");
scanf("%d",&m);
printf("Enter the number of columns in the matrix\n");
scanf("%d",&n);
printf("Enter the elements in the matrix\n");
a = create(m,n);
read(a,m,n);
printf("The sum of the elements in the matrix is %d", findSum(a,m,n));
return 0;
}
Post A Comment:
0 comments: