SUVAM ROY SUVAM ROY - 2 months ago 13
C Question

Unable to store data in an array

I want to add the elements of a 2D array row wise and then the summation I get want to store in another array. Like:: An array of 3 rows and 3 columns..
{1,2,3}=>6,{2,3,4}=>9,{5,6,7}=>18 and now I wanna store the values(6,9,18) in another array.What should I do?I could only able to sum up row wise.Should I use malloc? Please do help.

#include<stdio.h>
void main(){
int i,j,k,sum=0;
int array[3][3]={
{1,2,4},
{4,5,6},
{7,8,9}
};
int array2[k];
for(i=0;i<=2;i++){
for(j=0;j<=2;j++){
sum=sum+array[i][j];
}
printf("sum is %d in row %d in array1 \n \n",sum,i);

sum=0;
}
}

Answer

If you know, that your array contains exactly 3 rows, you don't need to use any malloc. Just declare the resulting array like this: int array2[3] and then, store your sums in this array like this: array2[i] = sum; (after inner loop, where j is the iterator). To make your code more predictable, set sum to zero before the inner loop, when you count the sum.

Comments