Question

My code works I just want to know what to do to get it to actually look like a diamond. Everything is just left justified like this:

 * 
 * * 
 * * * 
 * * * 
 * * 
 * 

But I want it to look like this:

   * 
  * * 
 * * * 
 * * * 
  * * 
   * 
public static void s3(int num, int len)
   {
      for(i = 1; i<=num; i++)

         System.out.print(" " + "*");
      System.out.print(" ");
      System.out.println();

      if(num < len)
         s3(num + 1, len);

      for (j = 1; j<= num; j++)

         System.out.print(" " + "*");
      System.out.print(" ");
      System.out.println();
   }
}

should I use print f to format or what? I've had a long day of frustrating programming and just need some help. Thanks!

Was it helpful?

Solution

The solution is not really a beauty, but it's 4am here and that's all I can provide for now ;)

About recursion you are very welcome to think how you can do it on your own.

public static void s3(int len) {
    for (int i = 0; i <= len; i++) {
        for (int j = len; j > i; j--) {
            System.out.print(" ");
        }

        for (int j = 0; j < len - (len - i); j++) {
            System.out.print(" *");
        }

        System.out.println("");
    }
    for (int i = 0; i <= len; i++) {

        for (int j = 0; j < (i); j++) {
            System.out.print(" ");

        }

        for (int j = len; j > i; j--) {
            System.out.print(" *");

        }

        System.out.println("");
    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top