Wednesday, 24 February 2016

C program to print the sum of each row and each column of a matrix using dynamic array

#include<stdio.h>
#include<conio.h>
#include<malloc.h>

void main()
{
int **a,r,c,i,j,sum=0;
clrscr();
//Accepting size of row and column
printf("Enter size of row n");
scanf("%d",&r);
printf("Enter size of column n");
scanf("%d",&c);

//Allocating memory to array
a=(int **)malloc(r*sizeof(int *));
for(i=0;i<r;i++)
a[i]=(int *)malloc((c+1)*sizeof(int));

printf("Enter array elements n");

for(i=0;i<r;i++)
for(j=0;j<c;j++)
scanf("%d",&a[i][j]); //Accepting array elements from user

 for (i = 0; i < r; i++)
    {
 for (j = 0; j < c; j++)
        {
sum = sum + a[i][j] ;
        }
        printf("Sum of the %d row is = %d\n", i, sum);
        sum = 0;
    }
    sum = 0;
for (j = 0; j < c; j++)
    {
 for (i = 0; i < r; i++)
        {
sum = sum + a[i][j];
        }
        printf("Sum of the %d column is = %d\n", j, sum);
        sum = 0;
}

getch();
 }

No comments:

Post a Comment