Skip to content
Advertisement

Nested for-loop problem with descending number

I’m trying to figure out how to complete this problem. I’m shooting for:

3 3 3 3 3 
3 2 2 2 3
3 2 1 2 3
3 2 2 2 3
3 3 3 3 3

and I have the following code, which gives me this:

3 2 1 
3 2 1 
3 2 1
3 2 
3 

I think I’m close but can some one help?

    System.out.print("Enter the length of the pattern size: ");
    int size = scan.nextInt();
    System.out.println();
    for (int row=size*2-1; row >= 1; row--) { 
        for (int col=size*2-1; col >= 1; col--) {
            if (col <= size && row >= size-col+1 )
                System.out.print(col + " ");
        }
        System.out.println();
    }
}

}

Advertisement

Answer

I think the problem is with the logic you used. I made an algorithm inspired by another idea, maybe it will help you. I am sure there is an easier way then this, but this works as well with all numbers.

example for input 4: get x and y value and after the smallest coordinate(either x or y) is the indicator which number should be printed. x and y increases from the top left corner downwards starting from 0.

If x or y coordinate is 0 for example we know it is going to be 4. if x coordinate is 2 but y is 3, we still take the smaller one: the number printed out will be in the second circle of numbers, number 2.

// 4 4 4 4
// 4 3 3 3
// 4 3 2 2
// 4 3 2 1

System.out.print("Enter the length of the pattern size: ");
int size = scan.nextInt();
System.out.println();

int len = size*2-1; // length of column and row

for (int row = 0; row < len; row++) {

    int x = (row%size); // get x coordinate (row)
    if (row >= size) x = (size-2) - x; // flip coordinate

    for (int col = 0; col < len; col++) {
        int y = (col%size); // get y coordinate (col)
        if (col >= size) y = (size-2) - y; // flip coordinate

        int val = size - Math.min(x, y); // get minimum coordinate
        System.out.print(val + " ");
    }

    System.out.println();
}
8 People found this is helpful
Advertisement