Joe Neathery
Joe Neathery

Reputation: 1

How to make a downward number triangle in Java?

So I have to write a program that displays this number pattern:

123456
 12345
  1234
   123
    12
     1

Here is the program I have:

public class PatternD {
    public static void main(String[] args) {
        for(int i=6;i>=0;i--){
            for(int j=6;j>=1;j--){
                if(j>i){
                    System.out.print(" ");
                }else{
                    System.out.print(j);
                }

            }
            System.out.println();
        }
    }
}

This displays:

654321
 54321
  4321
   321
    21
     1

I need to flip some numbers and I've tried a bunch of different things, but I'm still lost. Any help is appreciated. Thanks.

Upvotes: 0

Views: 812

Answers (2)

Jason
Jason

Reputation: 11822

First, your outer loop should stop when i = 0, not when i = -1. Second, the number you need to print is i - j + 1.

public class PatternD {
    public static void main(String[] args) {
        for(int i=6;i>0;i--){
            for(int j=6;j>=1;j--){
                if(j>i){
                    System.out.print(" ");
                }else{
                    System.out.print(i - j + 1);
                }

            }
            System.out.println();
        }
    }
}

Upvotes: 2

user4668606
user4668606

Reputation:

Use two loops inside the first loop: one to add the spaces and one to print the numbers.

Upvotes: 0

Related Questions