jeudi 16 novembre 2017

Creating a number pyramid: getting the if-conditions right

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.

Then I added to the if that increases:

|| ( (p%2==1) && (p<=q/2+1) && (p!=1) )

But that somehow changes my even rows, which were working fine. I don't really get why.

Pyramid is supposed to look like this:

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

Wit the added condition like this

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

Without it looked this

         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

Aucun commentaire:

Enregistrer un commentaire