Search code examples
loopsfor-loopif-statementiterationpyramid

Creating a number pyramid by iteration


I am trying to make a number pyramid, but have some problem to find the right conditions.

int n = scanner.nextInt();
int a;
for(int q = 1; q <= n; q++)
{
    for(int space = 0; space < n-q; space++){
        System.out.print(" ");
    }
    a = 1;
    for(int p = 1; p <= q; p++){
        if((p <= q / 2 && p != 1)){                         
            a++;
        }
        else if((p != 1) && (p > q / 2 + 1)){
            a--;
        }
        System.out.print(a+" ");
    }
    System.out.println();
}

It creates a proper pyramid, but the uneven rows stop to increase to early.

Supposed outcome:

    1
   1 1
  1 2 1
 1 2 2 1
1 2 3 2 1

The outcome of my code is

         1
        1 1
       1 1 0
      1 2 2 1
     1 2 2 1 0
    1 2 3 3 2 1
   1 2 3 3 2 1 0
  1 2 3 4 4 3 2 1
 1 2 3 4 4 3 2 1 0
1 2 3 4 5 5 4 3 2 1

Solution

  • Try this, it works:

    int number = 5;
    for (int i = 0; i < number; i++) {
        int x = 1;
        for (int j = 0; j < (number + i); j++) {
            if (j < number - i - 1) {
                System.out.print(" ");
            } else {
                System.out.print(x);
                if (j < (number - 1)) {
                    x++;
                } else {
                    x--;
                }  
            }
        }
        System.out.println(" ");
    }