How to set a specific column of a matrix to zero if a particular element in that column is zero with Java

1 Answer

0 votes
public class MatrixSpecificColumnToZero_Java {
    public static void printMatrix(int[][] matrix) {
        int rows = matrix.length;
        int cols = matrix[0].length;
        
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                System.out.printf("%4d ", matrix[i][j]);
            }
            System.out.println();
        }
    }
 
    public static boolean matrixColumnIncludesNumber(int[][] matrix, int col, int number) {
        int rows = matrix.length;
        
        for (int i = 0; i < rows; i++) {
            if (matrix[i][col] == number) {
                return true;
            }
        }
        return false;
    }
 
    public static void setMatrixColumnToZero(int[][] matrix, int col) {
        int rows = matrix.length;
        
        for (int i = 0; i < rows; i++) {
            matrix[i][col] = 0;
        }
    }
 
    public static void main(String[] args) {
        int[][] matrix = {
                { 4,  7,  9, 18, 29, 0},
                { 1,  9, 18, 99,  4, 3},
                { 9, 17, 89,  0,  7, 5},
                {19, 49,  0,  1,  9, 8},
                {29,  4,  7,  9, 18, 6}
        };
 
        int col = 2;
        
        if (matrixColumnIncludesNumber(matrix, col, 0)) {
            setMatrixColumnToZero(matrix, col);
        }
 
        printMatrix(matrix);
    }
}

  
  
/*
run:
  
   4    7    0   18   29    0 
   1    9    0   99    4    3 
   9   17    0    0    7    5 
  19   49    0    1    9    8 
  29    4    0    9   18    6 
  
*/

 



answered Jul 11, 2024 by avibootz
edited Jul 13, 2024 by avibootz
...