Home » Java » Fill up a two-dimensional array Java

Fill up a two-dimensional array Java

Posted by: admin October 22, 2018 Leave a comment

Questions:

I have a task, to fill up a two-dimensional array in a specific way, so it should make an output like shown on the picture, for example:

1 0 0 0 0 0 1
0 1 0 0 0 1 0
0 0 1 0 1 0 0
0 0 0 1 0 0 0
0 0 1 0 1 0 0
0 1 0 0 0 1 0
1 0 0 0 0 0 1

This is what I did and it works fine:

public class TwoDArrays {
    public static void main(String[] args) {
        FillUpTwoDArray(7, 7);
    }

    public static void FillUpTwoDArrays(int rows, int columns) {
        int twoD[][] = new int[rows][columns];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                twoD[i][j] = 0;
                if (i == j) {
                    twoD[i][j] = 1;
                }
                if (i + j == rows - 1) {
                    twoD[i][j] = 1;
                }
            }
        }
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++)
                System.out.print(twoD[i][j] + " ");
            System.out.println();
        }
    }
    ...
}

My headache starts here:

1 1 1 1 1 1 1
0 1 1 1 1 1 0
0 0 1 1 1 0 0
0 0 0 1 0 0 0
0 0 1 1 1 0 0
0 1 1 1 1 1 0
1 1 1 1 1 1 1

Maybe logic looks obvious for someone, but I have no clue at all, how to explain this to JVM. I don’t ask you for a solution-ready answer, some hints would be perfect, thank you in advance!

Answers: