1

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.

floval
  • 31
  • 2

4 Answers4

1

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();
}
Spencer
  • 176
  • 5
  • Thank you! This might be a dumb question, but if int i starts out as 0, and decreases by -1, why doesn't (i) print out as -1, -2 etc.? – floval Feb 08 '16 at 17:50
  • Int i starts out at nr, not 0. It decreases until the condition inside the for loop, i > 0, is false. That condition becomes false when i decrements from 1 to 0, and the loop breaks. – Spencer Feb 08 '16 at 18:20
1

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?

0

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();
}
Community
  • 1
  • 1
0

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();
}
Andreas
  • 154,647
  • 11
  • 152
  • 247