java - A pyramid of numbers starting with 0 ending with 9 -


i print pyramid of numbers starting 0 , ending 9, when equal 9, program should start on again 0 9 , on...

here have tried:

public static void main(string[] args) {      (int = 0; < 10; += 2) {         (int j = 0; j < 10 - i; j += 2) {             system.out.print(" ");         }         (int k = 0; k <= i; k++) {             system.out.print(" " + k);         }         system.out.println();     } }         

which printed

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

but need this..

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

you printing k starts 0 every iteration of i printing 0 1 2 3.. everytime. instead create local variable initialized 0 , print , increase 1 everytime. in case want start counter 0 when counter value greater 9 can add check including if(counter > 9) counter = 0;. added code below:

int counter = 0; (int = 0; < 10; += 2) {  (int j = 0; j < 20 - i; j++) {   system.out.print(" ");  }  (int k = 0; k <= i; k++) {   system.out.print(" " + counter++);   if(counter > 9) counter = 0;  }   system.out.println(); } 

output

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

demo


Comments