I am supposed to write a method to display a pattern as follows:

________1
_______21
______321
_____4321
____54321
___654321
__7654321
_87654321
987654321

(underscores are simply placeholders to show alignment on my post they are not actually part of the printout)

My program works and prints the aforementioned code correctly, however it does not right aligh to match up the "1"'s I know that I have to use a printf but im not quite sure what specifiers I need any help would be greatly appreciated, this is what I have so far:

public class displayPattern {

    public static void main(String[] args) {

    	displayPattern(9);
    }

    public static void displayPattern(int n)
    {
    	for(int i=1;i<=n;++i)
    	{
    		for(int j=i;j>0;--j)
    		{
    			System.out.printf(" "+j);
    		}
    		   System.out.printf("\n");
    	}
    	}
}

Edited 4 Years Ago by DanOath: n/a

Try to iterate over the value of n in the second loop instead of i
then use an if else statement
if the value of j is less than or equal to i print only the value of j
else print a space(" ")

Try to iterate over the value of n in the second loop instead of i
then use an if else statement
if the value of j is less than or equal to i print only the value of j
else print a space(" ")

Thanks SO MUCH it worked and this is what I used:

public class displayPattern {

    public static void main(String[] args) {

    	displayPattern(9);
    }

    public static void displayPattern(int n)
    {
    	for(int i=1;i<=n;++i)
    	{
    		for(int j=n;j>0;--j)
    		{
    			if (j <= i)
    			System.out.print(j);
    			else
    			System.out.printf(" ");
    		}
    		   System.out.printf("\n");
    	}
    	}
}

Edited 4 Years Ago by DanOath: n/a

This question has already been answered. Start a new discussion instead.