Traverse the matrix in Java
- A matrix will be in M x N format.
- So what we need to do is, get value of indexes from 0,0 to m,n.
- Itreate the two dimensional array as follow
take 1(i) and traverse j till j < N
.
.
till M(i) and traverse j till j < N
PrimeNumberCheck.java
public class TraverseMatrix {
private static final int M = 3;
private static final int N = 3;
public static void main(String[] args) {
TraverseMatrix app = new TraverseMatrix();
int matrix[][] = app.createMatrix();
app.printMatrix(matrix);
app.normalTraverse(matrix);
}
private void normalTraverse(int[][] matrix) {
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
System.out.print(matrix[i][j]);
System.out.print(", ");
}
}
}
private int[][] createMatrix() {
int matrix[][] = new int[M][N];
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
matrix[i][j] = (int) (Math.random() * 100 + 1);
}
}
return matrix;
}
private void printMatrix(int[][] matrix) {
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
System.out.print(matrix[i][j]);
System.out.print(" ");
}
System.out.println(" ");
}
}
}
No comments:
Post a Comment