Shiva
Shiva

Reputation: 29

pyramid program using numbers in java and print in reverse order as well

I want the output as shown below can anyone suggest me how to write that program, tried a lot but not getting as expected

1

2*3

4*5*6

7*8*9*10

7*8*9*10

4*5*6

2*3

1

this is the program I tried

public class Triangle_program2 {

    public static void main(String[] args) {
        int end=4;
        int i,j,num=1;
        for(i=0;i<end;i++)
        {
            for(j=0;j<=i;j++)
            {
                System.out.print(num+ " ");
                num++;
            }
            System.out.println();
        }
        num=num-1;
        for(i = end; i >= 1; --i) 
        {
            for(j = 1; j <= i; ++j) 
            {
                System.out.print(num+ " ");
                num--;
            }
            System.out.println();
        }                   
    }

}

and this is the result I am getting

1

2 3

4 5 6

7 8 9 10

10 9 8 7

6 5 4

3 2

1

Upvotes: 0

Views: 299

Answers (2)

Veselin Davidov
Veselin Davidov

Reputation: 7081

A nice solution would be to have the inner loop always go from num to num+i (in both cases). I think this makes the code a bit easier to understand and the two parts of the program look similar.

    public static void main(String[] args) {
      int end=4;
      int i,j,num=1;

      for(i=0;i<end;i++)
      {
          for(j=num;j<=num+i;j++)
          {
              System.out.print(j+" ");
          }   
          num=j;
          System.out.println();
      }

      for(i = end; i >= 1; --i) 
      {
          num=num-i; 
          for(j=num;j<num+i;j++)
          {
              System.out.print(j+" ");
          }
          System.out.println();
      }                   
  }         

The only difference is that in the fast part you go num=num+i; and in the second part you go num=num-i; There is one num=num+i outside the loop to do the calculating properly without adding a check in the loop;

Demo

Upvotes: 0

vCillusion
vCillusion

Reputation: 1799

We need to focus on the transition of printing

7 8 9 10

10 9 8 7

Demo

Below solution works with modifications to looping logic to decrement the counter based on the level of the pyramid in your code:

public class MyClass {
  public static void main(String args[]) {
    int end=4;
    int i,j,num=1;
    for(i=0;i<end;i++)
    {
        for(j=0;j<=i;j++)
        {
            System.out.print(num+ " ");
            num++;
        }
        System.out.println();
    }
    for(i = end; i >= 1; --i) 
    {
        num-=i;
        for(j = 1; j <= i; ++j) 
        {
            System.out.print(num + " ");
            num++;
        }
        num-=i;
        System.out.println();
    }   
  } 
}

Upvotes: 1

Related Questions