Java print a pattern with nested for loop

Bence

I am struggling to build an algorithm that would print the much needed pattern. The code is the following:

public static void printPatternH(int size)
{
    for (int row = 1; row <= size; row++)
    {
        for (int col = 1; col <= 2*size; col++)
        {
            if (col > size + row - 1) {
                continue;
            }
            if (col <= size) {
                System.out.print((row + col >= size + 1 ? (row + col)%size : " ") + " ");
            }
            else {
                System.out.print((row + col >= size + 1 ? (row + size)%col : " ") + " ");
            }                
        }
        System.out.println();
    }
}

The result is:
enter image description here

I understand that if size is 9 the last number in the middle will be 0 as (row + size)%col = 0, however I couldn't figure out a way to modify it without changing the rest of the values.

saka1029

Change

(row + col)%size

to

(row + col - 1) % size + 1

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related