Java pyramid program print numbers?

时间:2015-06-30 13:50:03

标签: java

How to write a java program to print below the pattern?

     0
    1 2
   3 4 5
  6 7 8 9

I tried this.

for (int i = 0; i < levels; i++) {
    for (int s = levels; s > i; s--) {
        // add spacing
        System.out.print(" ");
    }
    for (int j = 0; j <= i; j++) {
        // display/add star
        System.out.print(i+j+" ");
    }
    // add new line
    System.out.println("");
}

1 个答案:

答案 0 :(得分:2)

just make a small modification.i declared a variable int z = 0; each time it print a character increment z by one.because this pattern goes like 0,1 ,2 ,3 ,4 ,++++.......

int levels = 4;
int z = 0; // this make it easy
for (int i = 0; i < levels; i++) {
    for (int s = levels; s > i; s--) {
        System.out.print(" ");
    }
    for (int j = 0; j <= i; j++) {

        System.out.print(z + " ");
        z++;
    }
    System.out.println("");
}

the output

    0 
   1 2 
  3 4 5 
 6 7 8 9