I have been asked to write a method that prints out the following pattern:

XXXXXXX
XXXXXX
XXXXX
XXXX
XXX
XX
X
instead of left-justified, i'm supposed to write a "right-justified" pattern.

I am not quite sure how i can write codes to insert the " " to get the above pattern.

So far, my codes are like these:

public void drawInvertedTriangle( int n )
{
for(int x=n; x>0; x--)
{ 
for(int y=1; y<=x;y++)
{
System.out.print("X");
}
System.out.println();
}
}

Any help would be appreciated, thank you!

Do you want something like this:

XXXX
 XXX
  XX
   X

If so then you can do something like:

  • Run an outer loop which will move from 1 to n.
  • Run an inner loop which will move from 1 to n.
  • If the inner loop counter is less than the outer loop counter, print a space or else print the required character.
  • Print a newline at the end of the inner loop.