how to ignore values in a matrix?

I'm trying to get the sum of a row in a matrix, whilst ignoring the negative values. So far, I have

int main() {
    int matrix[n][l] = { {8, 4, -7, - 2, 3}, {1, 8, -9},
        {2,  -8,  7, 9} };
    int row, col, sum;

    for (row = 0; row < n; row++)
    {
        sum = 0;
        for (col = 0; col < l; col++)
            sum = sum + matrix[row][col];
        cout << "Row sum " << row + 1 << " = " << sum << endl;
    }

    return 0;
}

I've tried using

while(matrix>0)
continue;

and it just ends up giving me junk in the output.

1 answer

  • answered 2020-10-01 05:29 Mumtozbekov

    int matrix[n][l] = { {8, 4, -7, - 2, 3}, {1, 8, -9},
    {2,  -8,  7, 9} };
    int row, col, sum;
    for (row = 0; row < n; row++)
    {
        
        sum = 0;
        for (col = 0; col < l; col++)
            sum = sum + (matrix[row][col]>0)*matrix[row][col];
        cout << "Row sum " << row + 1 << " = " << sum << endl;
    }
    return 0;
    }