
Hi, I want to know how the code to print the pyramid below works. It uses nested for loops.
Pyramid:
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
6 5 4 3 2 1 2 3 4 5 6
7 6 5 4 3 2 1 2 3 4 5 6 7
8 7 6 5 4 3 2 1 2 3 4 5 6 7 8
9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9

Java Pyramid of Numbers
class Pyramid{
public static void main(String[] args){
int x = 9;
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();
}
}
}

Thank you. But I keep don't understanding how the spaces between numbers are working

instead of using System.out.print with conditional, you could do this: this will allocate five spaces for the numbers.
class Pyramid{
public static void main(String[] args){
int x = 9;
for (int i = 1; i <= x; i++) {
for (int j = 1; j <= x - i; j++)
System.out.printf("%5s", "");
for (int k = i; k >= 1; k--)
System.out.printf("%5d", k);
for (int k = 2; k <=i; k++)
System.out.printf("%5d", k);
System.out.println();
}
}
}