Home > Back-end >  how to print 3x3 2d array from numbers 1-9 without declaring and initializing vectors In Java?
how to print 3x3 2d array from numbers 1-9 without declaring and initializing vectors In Java?

Time:10-06

I have my java solution for printing out numbers 1-9 in a 3x3 matrix below:

     // declare and initialize a 3x3 matrix
    int matrix[][] = 
    { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
  
  // display matrix using for loops
  // outer loop for row
  for(int row =-0; row <matrix.length; row  ) {
    // inner loop for column
    for(int column=0; column <matrix[row].length; column  ) {
      System.out.print(matrix[row][column]   " ");
    }
    System.out.println(); // new line
  }

So I declared and Intialized a 3*3 vector (Array or matrix) in the code above.

But I want to do print out 3x3 2d array from numbers 1-9 without declaring and initializing vectors.

How do I approach this problem?

CodePudding user response:

Unless I'm missing something, you could use a loop from 1 to 9 and print a newline every third term by testing if the number is divisible by 3 (e.g. modulo 3 is 0). Like,

for (int i = 1; i < 10; i  ) {
    System.out.printf("%d ", i);
    if (i % 3 == 0) {
        System.out.println();
    }
}

No arrays (or vectors) required.

Or, you could just print the values instead.

System.out.println("1 2 3");
System.out.println("4 5 6");
System.out.println("7 8 9");
  • Related