Nostradamus
Nostradamus

Reputation: 13

How do I print this specific pyramid in Java?

I desire a code output that looks like this:

6 5 4 3 2 1
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1

Keep in mind that my code takes in the size of the pyramid through input before

My code now looks like:

for(int numRows=sizePyr;numRows>=1;numRows--){
    for(int i=sizePyr;i>=numRows;i--){
        System.out.print(i + " ");
    }
    System.out.println();
}

Upvotes: 0

Views: 67

Answers (2)

MT756
MT756

Reputation: 629

Changing the nested for loop to for (int i = numRows; i >= 1; i--) fixed the issue

You want to start printing i with the current numRows value, then work the way down to 1.

Your current code start printing i with sizePyr (which is a constant 6 throughout the function), then work the way down to numRows.

    for(int numRows=sizePyr;numRows>=1;numRows--){
        for(int i=numRows; i >= 1; i--){
            System.out.print(i + " ");
        }
        System.out.println();
    }

Upvotes: 1

Scott Hunter
Scott Hunter

Reputation: 49803

For the first line, you want to start with sizePyr (as your inner loop does), but want to end with 1 (which your loop decidedly does not). In fact, every line should end with 1. Change your loop to reflect this.

Upvotes: 1

Related Questions