Paul19
Paul19

Reputation: 13

Printing Reverse Triangle with Numbers - Java

I have some problem printing a reverse triangle I want to achieve, like this pattern:

******
***
*

But my goal is to achieve that pattern with this numbers:

333221
221
1

So, this is my code so far:

int x = 1;
for(int r=0;r<3;r++)
{
    x=x+r;
    for(int c=0;c<x;c++)
    {
        System.out.print("*");
    }
    x+=1;
    System.out.println();
}

Which the output is upright like this:

*
***
******

I want to make the pattern reverse with the numbers as it shown above.

Can anyone give me some idea how to deal with it? Thanks!

Upvotes: 0

Views: 7035

Answers (4)

Paris Tao
Paris Tao

Reputation: 365

@Test
public void reverseTriangle(){
    int num = 3;
    for (int i = num; i > 0; i--) {
        this.draw(i);
        System.out.println();
    }
}

private void draw(int num) {
    int total = 0;
    for (int i = 0; i <= num; i++) {
        total = total + i;
    }
    for (int i = 0; i < total; i++) {
        System.out.print("*");
    }
}

Upvotes: 0

DeiAndrei
DeiAndrei

Reputation: 947

This is how i would do it:

    for (i = 3; i > 0; i--) {

        for (j = i; j > 0; j--) {

            for (c = j; c > 0; c--) {

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

    }
  • first loop: you want to print 3 lines;
  • second loop: each line has i distinct numbers
  • third loop: print number j j times

Upvotes: 1

Nik Kashi
Nik Kashi

Reputation: 4596

        int depth = 3;
        for (int r = depth + 1; r >= 0; r--) {
            for (int c = 0; c < r; c++)
                for (int b = 0; b < c; b++)
                    System.out.print("*");
            System.out.println();
        }

Upvotes: 0

Dici
Dici

Reputation: 25950

You just need to reverse the order of your loops and decrement x instead of incrementing it. I change the code a bit though :

int level = 3;
for(int r=level ; r>0 ; r--) {
    for(int c=r ; c>0 ; c--) 
        for (int x=0 ; x<c ; x++)
            System.out.print("*");
    System.out.println();
}

Upvotes: 0

Related Questions