Search code examples
javaloopsnested-loopsconditional-operatorascii-art

Pyramid of numbers in Java


I am trying to print a pyramid in Java that looks something like this:

                9
              8 9 8
            7 8 9 8 7
          6 7 8 9 8 7 6
        5 6 7 8 9 8 7 6 5
      4 5 6 7 8 9 8 7 6 5 4
    3 4 5 6 7 8 9 8 7 6 5 4 3
  2 3 4 5 6 7 8 9 8 7 6 5 4 3 2
1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1

I was looking for ways to solve this on the internet and I stumbled across this :

class Pyramid {
    public static void main(String[] args) {
        int x = 7;
        for (int i = 1; i <= x; i++) {
            for (int j = 1; j <= x - i; j++)
                System.out.print("   ");
            for (int k = i; k >= 1; k--)
                System.out.print((k >= 10) ? +k : "  " + k);
            for (int k = 2; k <= i; k++)
                System.out.print((k >= 10) ? +k : "  " + k);
            System.out.println();
        }
    }
}

Could anyone please help me understand this? Here' what I've figured out :- The outer loop increments till 7 at the same time the inner j loop increments upto x - i which is 6 for the first iteration of the outer loop , then 5 ...and so on .. So basically the left side of the pyramid is just an inverted triangle of blank spaces.

I am having trouble figuring out what is happening in the other two nested loops and the the strange looking if - else parts inside the print statements.


Solution

  • Let's go through this step by step. As you've already figured out, x is a variable representing the height of the pyramid.

    then, as you also correctly found out, the first loop creates the indentation of the current line of numbers

    the second loop will now write the left half of the numbers, but If I got it right, it will start with the highest number and decrement, and then the third loop will increment the numbers again, creating a slightly different pyramid than the one you're looking for.

    now, the strange looking if-else parts, as you're calling them are the the ternary conditional operator, and the only purpose they're fulfilling in this code is fixing the number spacing when the pyramid contains numbers >= 10 by omitting the leading whitespace of the number. :)