Berchell
Berchell

Reputation: 41

Organizing 2D Interger Arrays in Java

I need to print out the following data using a multi-dimensional array:

5 4 3 2 1
10 9 8 7 6 
15 14 13 12 11
20 19 18 17 16 
25 24 23 22 21 

The programming language that I am using is Java. This is what I have so far:

public class Problem3 {

public static void main(String[] args) {


    int[][] prob3 = new int[5][5];


    for(int row = 0; row < prob3.length; row++){
        System.out.println();

        for(int col = 0; col < prob3[row].length; col++){
            prob3[row][col] = row * 5 + col + 1; 

            System.out.print(prob3[row][col] + " ");
        }
    }

}

}

When I print this to the screen I get this:

1 2 3 4 5
6 7 8 9 10 
11 12 13 14 15 
16 17 18 19 20 
21 22 23 24 25

I am not sure how to manipulate the numbers so they display how I want them. I really want to understand how this works. Let me know if I am doing this completely wrong. Thanks for the help in advance.

Upvotes: 0

Views: 48

Answers (1)

Quijx
Quijx

Reputation: 366

If you want iterate through the columns backward, you have to set you start value of the column-loop to the last index, check whether it's still bigger or equal to 0 and decrease col every iteration.
Like that:

int[][] prob3 = new int[5][5];

    for (int row = 0; row < prob3.length; row++) {
        System.out.println();

        for (int col = prob3[row].length - 1; col >= 0; col--) {
            prob3[row][col] = row * 5 + col + 1;

            System.out.print(prob3[row][col] + " ");
        }
    }

Upvotes: 2

Related Questions