Sami hanna Sami hanna - 4 months ago 10
Java Question

A pyramid of numbers starting with 0 ending with 9

I would like to print a pyramid of numbers starting with 0 and ending with 9, when it equal 9, program should start over again from 0 to 9 and so on...

Here is what I have tried:

public static void main(String[] args) {

for (int i = 0; i < 10; i += 2) {
for (int j = 0; j < 10 - i; j += 2) {
System.out.print(" ");
}
for (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 I need this..

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

Answer

You are printing k which starts from 0 for every iteration of i printing 0 1 2 3.. everytime. Instead create a local variable initialized to 0 and print it and also increase it by one everytime. In your case you want to start the counter from 0 when counter value is greater than 9 you can add a check for that by including if(counter > 9) counter = 0;. Added a code below:

int counter = 0;
for (int i = 0; i < 10; i += 2) {
 for (int j = 0; j < 20 - i; j++) {
  System.out.print(" ");
 }
 for (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