Given: int[][] matrix = new int[5][5] Using the statement above, write a nested loop to set matrix as follows: [0] [1] [2] [3] [4] [0] 1 0 0 0 0 [1] 0 2 0 0 0 [2] 0 0 3 0 0 [3] 0 0 0 4 0 [4] 0 0 0 0 5
//TestCode.java public class TestCode { public static void main(String[] args) { int[][] matrix = new int[5][5]; //Setting up the values for(int i = 0;i<matrix.length;i++){ for(int j = 0;j<matrix[i].length;j++){ if(i == j){ matrix[i][j] = i+1; } else{ matrix[i][j] = 0; } } } //Printing the matrix for(int i = 0;i<matrix.length;i++){ for(int j = 0;j<matrix[i].length;j++){ System.out.print(matrix[i][j]+" "); } System.out.println(); } } }
for(int i = 0;i<matrix.length;i++){ for(int j = 0;j<matrix[i].length;j++){ if(i == j){ matrix[i][j] = i+1; } else{ matrix[i][j] = 0; } } }
Get Answers For Free
Most questions answered within 1 hours.