We help IT Professionals succeed at work.

Output a diamond in java using for loops and while loops if required

Govinda2020
Govinda2020 used Ask the Experts™
on
I have written a program in Java for getting an output as a diamond.I dont want the numbers to be repeated.My program is

public class PyramidD
 {
  public static void main(String args[])
  {
   int r,c,m,n;
   n = Integer.parseInt(args[0]);
   for(r=1;r<=n;r+=2)
   {
    for(m=(n-r);m>0;m-=2)
     {
     System.out.print(" ");
     }
    for(c=1;c<=r;c+=2)
    {
     System.out.print(" "+c);
    }
     //System.out.print(" "+r);
     System.out.println(" ");
   }
    for(r=n;r>=0;r-=2)
   {
     for(m=1;m<=(n-r);m+=2)
    {
     System.out.print(" ");
    }
    for(c=r+1;c>=0;c-=2)
    {
     System.out.print(" "+c);
    }
     //System.out.print(" "+r);
     System.out.println(" ");
   }
  }
 }


My output when given n=8 is

     1
    1 3
   1 3 5
  1 3 5 7
 9 7 5 3 1
  7 5 3 1
   5 3 1
    3 1
     1

I dont want the numbers to be repeated.
I want an output as

     1
    2 3
   4 5 6
  7 8 9 10 and so on

Can somebody help me out of this.giving a solution like this
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
There are probably more elegant ways, but you could introduce a fifth int variable and everywhere you have  

System.out.print(" "+c);

you could instead print out that new variable and increment it by 1.

Author

Commented:
Onlyaymie Can you explain in brief.or show the script.
something like this

public class PyramidD
 {
  public static void main(String args[])
  {
   int r,c,m,n;
   int p=1;
   n = Integer.parseInt(args[0]);
   for(r=1;r<=n;r+=2)
   {
    for(m=(n-r);m>0;m-=2)
     {
     System.out.print(" ");
     }
    for(c=1;c<=r;c+=2)
    {
     //System.out.print(" "+c);
   System.out.print(" "+p);
   p = p + 1;

    }
     //System.out.print(" "+r);
     System.out.println(" ");
   }
    for(r=n;r>=0;r-=2)
   {
     for(m=1;m<=(n-r);m+=2)
    {
     System.out.print(" ");
    }
    for(c=r+1;c>=0;c-=2)
    {
     //System.out.print(" "+c);
   System.out.print(" "+p);
   p = p + 1;
    }
     //System.out.print(" "+r);
     System.out.println(" ");
   }
  }
 }