floval
floval

Reputation: 31

Upside-down triangle of numbers

I'm a beginner to Java and can't figure out how to print an upside down triangle of numbers. The numbers should decrease in value by 1 for each row. Ex. Number of rows: 6;

Print:

666666
55555
4444
333
22
1

So far this is what I came up with; (int nr is scanned input from user)

for (int i = 1; i <= nr; i++) {
    for (int j = 1; j <= nr; j++) {
        System.out.print(nr);
    }
    nr--;
    System.out.println();
}

By having nr--; the loop gets shorter and I cant figure out how to keep the loop going for nr-times, yet still decreasing the amount of numbers printed out.

Upvotes: 1

Views: 1600

Answers (4)

user15495739
user15495739

Reputation:

In this case, you can use a single while loop and two decreasing variables:

  • i - number of the row - from 6 to 1
  • j - number of repetitions in the row - from i to 1:
int i = 6, j = i;
while (i > 0) {
    if (j > 0) {
        // print 'i' element 'j' times
        System.out.print(i);
        --j;
    } else {
        // start new line
        System.out.println();
        j = --i;
    }
}

Output:

666666
55555
4444
333
22
1

See also: Printing a squares triangle. How to mirror numbers?

Upvotes: 1

Your problem is that you are changing nr, try:

int original_nr = nr;
for (int i = 1; i <= original_nr; i++) {
    for (int j = 1; j <= nr; j++) {
        System.out.print(nr);
    }
    nr--;
    System.out.println();
}

Upvotes: 0

Andreas
Andreas

Reputation: 159270

You can't decrease nr and still use it as upper limit in the loops. You should in fact consider nr to be immutable.

Instead, change outer loop to count from nr down to 1, and inner loop to count from 1 to i, and print value of i.

for (int i = nr; i > 0; i--) {
    for (int j = 0; j < i; j++) {
        System.out.print(i);
    }
    System.out.println();
}

Upvotes: 0

Spencer
Spencer

Reputation: 174

You are right in that you need to write a loop to print a line for each number, starting at nr and decreasing by 1 until you get to 0. But you also have to print a variable number of numbers at each line. To do that, a nested loop could be used to print the number the amount of times necessary.

Since you start printing at nr and decrease until you reach 1, you could try writing an outer loop that decrements rather than increments. Then use a nested loop to print the number the required number of times. For example:

for (int i = nr; i > 0; i--) {
    for (int j = 0; j < i; j++) {
        System.out.print(i);
    }
    System.out.println();
}

Upvotes: 1

Related Questions