user7124275
user7124275

Reputation: 41

Printing each elements of one row on separate lines?

This is my question: Assume a two-dimensional array of ints called 'myInts'. Write a code snippet that will print each of the elements of row m on a separate line. You may assume that m is not out of bounds.

This is the work I have done but I am not sure I am going in the right direction...

for (int i = 0; i < myInts.length; i++) {
    for (int j = 0; j < myInts[i].length; j++) {
        System.out.print (myInts[i][j]);

        if(j < myInts[i].length - 1) {
            System.out.print(" ");
        }
    }

    System.out.println();
}

Upvotes: 0

Views: 233

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522635

Because your requirement is only to print the values of a given row m, I think you only need a single for loop, to iterate over that single row:

public void printRow(int[][] array, int m) {
    for (int i=0; i < array[m].length; ++i) {
        System.out.println(array[m][i]);
    }
}

I didn't bother checking the bounds of input m, because you said we don't need to. But in any case, printRow() would throw an ArrayIndexOutOfBoundsException should the index m be out of bounds.

Upvotes: 3

Related Questions