Samit Basu
Samit Basu

Reputation: 21

Pyramid Pattern for

click to see image

Hi I am new to JAVA.I have been practising but got stuck at a pyramid problem.Please help how to do it.This should be the output when number of rows which the user should input=5.

I have tried myself but could only incorporate the # not the @

    public static void main(String args[]){
    int  i,j,k;int cnt=0;

    for(i=1;i<=x;i++)
    {
        System.out.print(" ");
        for(j=1;j<=x-i;j++)
        {
            System.out.print("  ");
        }

        for(k=i;k>0;k--)
        {
            if(cnt%2==0)
            System.out.print(" #  ");//even position
            else
            System.out.print(" @  ");//odd position
            cnt++;
        }
        System.out.println(" ");
    }

 }

Upvotes: 2

Views: 86

Answers (1)

SatyaTNV
SatyaTNV

Reputation: 4135

Change your for loops to

  for(j=1;j<=x-i;j++)
    {
        System.out.print("   ");
    }
  for(k=i;k>0;k--)
    {
        if(cnt%2==0)
        System.out.print("#     ");//even position
        else
        System.out.print("@     ");//odd position
        cnt++;
    }

Output:

            #
         @     #
      @     #     @
   #     @     #     @
#     @     #     @     #

Upvotes: 2

Related Questions