Home > Mobile >  In this question im trying to solve a problem about for loops
In this question im trying to solve a problem about for loops

Time:01-11

In this question I'm looking for any row or column which its sum is more than 2,the first row or column which is found break through the loop and printing yes if there isn't any print no. The code works fine for printing the sum of each row and column but it can't define if the input matrix has any row or column with such quality.

#include <stdio.h>

int main()
{
int n,m,i,j;
int sum_r,sum_c;
int sw = 0;
scanf("%d%d",&m,&n);
int a [10][10];
for(i=0; i<m; i  )
{
    for(j=0; j<n; j  )
    {
        scanf("%d",&a[i][j]);
    }
}
for(i=0; i<m; i  )
{
    sum_r = 0;
    for(j=0; j<n; j  )
    {
        sum_r  = a[i][j];
        if(sum_r >= 2)
        {
            sw = 1;
        }
    }
}

for(i=0; i<n; i  )
{
    sum_c = 0;
    for(j=0; j<m; j  )
    {
        sum_c  = a[j][i];
        if (sum_c >= 2)
        {
            sw = 1;
        }
    }
}

if (sw = 1) printf("yes");
else printf("no");

return 0;

}

CodePudding user response:

For starters there is a typo in this if statement

if (sw = 1) printf("yes");

You have to use the comparison operator == instead of the assignment operator =

if (sw == 1) printf("yes");

Or simpler

if (sw) printf("yes");

If I have understood correctly then what you need is something like the following

for(i=0; !sw && i<m; i  )
{
    sum_r = 0;
    for(j=0; !( sum_r > 2 ) && j<n; j  )
    {
        sum_r  = a[i][j];
        if(sum_r > 2)
        {
            sw = 1;
        }
    }
}

for(i=0; !sw && i<n; i  )
{
    sum_c = 0;
    for(j=0; !( sum_c > 2 ) && j<m; j  )
    {
        sum_c  = a[j][i];
        if (sum_c > 2)
        {
            sw = 1;
        }
    }
}
  •  Tags:  
  • Related