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

1 Answer

0 votes
import java.util.Arrays;
 
public class MatrixSpecificRowToZero_Java {
    public static void printMatrix(int[][] matrix) {
        int cols = matrix[0].length;
        int rows = matrix.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 matrixRowIncludesNumber(int[][] matrix, int row, int number) {
        int cols = matrix[0].length;
        
        for (int j = 0; j < cols; j++) {
            if (matrix[row][j] == number) {
                return true;
            }
        }
        return false;
    }
 
    public static void setMatrixRowToZero(int[][] matrix, int row) {
        Arrays.fill(matrix[row], 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, 6, 1, 9, 8 },
            { 29, 4, 7, 9, 18, 6 }
        };
 
        int row = 2;
        
          
        if (matrixRowIncludesNumber(matrix, row, 0)) {
            setMatrixRowToZero(matrix, row);
        }
 
        printMatrix(matrix);
    }
}
 
 
  
  
/*
run:
  
   4    7    9   18   29    0 
   1    9   18   99    4    3 
   0    0    0    0    0    0 
  19   49    6    1    9    8 
  29    4    7    9   18    6 
  
*/

 



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