Search code examples
javafor-loopnested-loops

I'm having trouble making a diamond shape with loops


You have an input of n and that represents half the rows that the diamond will have. I was able to make the first half of the diamond but I'm EXTREMELY frustrated with the second half. I just can't seem to get it. I'm not here to ask for specific code I need, but can you point me in the right direction and give me some tips/tricks on how to write this? Also, if I'm going about this program the wrong way, feel free to tell me and tell me on how I should approach the program.

The diamonds at the bottom represent an input of 5. n-1 represents the spaces to the left of each asterisk. Thank you for your help!

 public static void printDiamond(int n)
  {
  for(int i=0;i<n;i++)
  {
      for(int a=0;a<(n-(i+1));a++)
      {
          System.out.print(" ");
      }
      System.out.print("*");
      for(int b=0; b<(i*2);b++)
      {
          System.out.print("-");
      }
      System.out.print("*");
      System.out.println();
  } 
}
    **    What I need              **   What I have currently
   *--*                           *--*
  *----*                         *----*
 *------*                       *------*
*--------*                     *--------*
*--------*
 *------*
  *----*
   *--*
    **

Solution

  • Just reverse your loop :

        for(int i=n-1;i>=0;i--)
        {
            for(int a=0;a<(n-(i+1));a++)
            {
                System.out.print(" ");
            }
            System.out.print("*");
            for(int b=0; b<(i*2);b++)
            {
                System.out.print("-");
            }
            System.out.print("*");
            System.out.println();
        }