I am supposed to write a program which fills a matrix (flag[][]
, here) with 0s and 1s such that the the given row and column sums are satisfied. The row and column sums are to be calculated by adding the fractional part of the elements of a[][]
. I wrote the code given below, which works when I run just this part of it:
#include<stdio.h>
#include<stdlib.h>
int main()
{int m=3;
int flag[3][3];
int rSum[] = {1,1,2};
int cSum[] = {2,1,1};
for(int i=0;i<m;i++)
{int k = 0;
for(int j=0;j<rSum[i];j++)
{
if(cSum[k] == 0)
{
j--;
k++;
}
else
{
flag[i][k] = 1;
cSum[k]--;
k++;
}
}
}
return 0;
}
But the whole code gives wrong output on running. The whole code:
#include<stdio.h>
#include<stdlib.h>
int main()
{
printf("Enter the size of matrix: ");
int m,n;
scanf("%d %d",&m,&n);
float a[m][n];
printf("Enter the elements: ");
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
scanf("%f",&a[i][j]);
}
}
float b[m][n];
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
b[i][j] = a[i][j] - (int)a[i][j];
printf("%f ",b[i][j]);
}
printf("\n");
}
printf("\n\n\n");
float rSum[m], cSum[n];
for(int i=0;i<n;i++)
{
cSum[i] = 0;
}
for(int i=0;i<m;i++)
{
rSum[i] = 0;
}
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
rSum[i] += b[i][j];
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cSum[i] += b[j][i];
}
}
printf("\nrSum:");
for(int i=0;i<m;i++)
{
printf("%f ",rSum[i]);
}
printf("\ncSum:");
for(int i=0;i<n;i++)
{
printf("%f ",cSum[i]);
}
int flag[m][n];
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
flag[i][j] = 0;
}
}
for(int i=0;i<m;i++)
{int k = 0;
for(int j=0;j<rSum[i];j++)
{
if(cSum[k] == 0)
{
j--;
k++;
}
else
{
flag[i][k] = 1;
cSum[k]--;
k++;
}
}
}
printf("\n\n\n");
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
printf("%d ",flag[i][j]);
}
printf("\n");
}
return 0;
}
Can anyone please point out the mistake I am making? Why is the first code working fine, but not the second one?
Also, my input for a[][]
was {1.2 , 3.4, 2.4, 3.9, 4.0, 2.1, 7.9, 5.6, 0.5}
.