L.T L.T - 3 months ago 13
Java Question

creating a simple symmetric table in java

I'm currently studying arrays in Java. However, I'm having trouble creating a symmetric table, something like the following:

enter image description here

Is there a simple solution to create an array like this? This is not homework but for an exam I'm studying for. I want to know how to do this.

Thanks in advance

Here is the code I have:

int [][] table = new int [5] [8];
for (i=0;i < 5; i ++)
{
table[i][0] = i+1;
}

for ( j = 0; j < 4; j ++)
{
table[ i ][ j ] = ;
}


It's not much code, but I don't know how to iterate through it so all the values are symmetric. I have filled the first row with values. I was thinking about looping to 4 in the columns so I'm in the half but then what do I do?

Answer

Your code is a beginning, but doesn't fill all values. You should nest your for-loops, and only fill the left part. The right entry can then be mirrored from the left entry. Try this:

public static void main(String[] args)
{
    int[][] table = new int[5][8];

    for (int row = 0; row < 5; row++)
    {
        for (int column = 0; column < 4; column++)
        {
            // left side entry [row][0..3]
            // each entry is 5 more than the entry left of it 
            table[row][column] = column * 5 + row + 1;

            // right side entry [row][7..4] mirrored from corresponding entry [row][0..3]
            // i.e. column 7 <- column 0, column 6 <- column 1, etc.
            table[row][7 - column] = table[row][column];
        }
    }

    for (int row = 0; row < 5; row++)
    {
        for (int column = 0; column < 8; column++)
        {
            System.out.format("%4d", table[row][column]);
        }
        System.out.println();
    }
}

Output:

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