Is there any other way to print solid rhombus with * using for loops

69 Views Asked by At

I am leaning Java, trying to solve the patterns in Java using for loop Solid Rhombus.

Print Format:

line 1 :5 Spaces *****(5 Stars) then 
Line 2 :4 Spaces *****
line 3 :3 Spaces *****
Line 4 :2 Spaces *****
Line 5 :1 Space *****

I tried for loop with nested for loop as below

public class SolidRombus {
  public static void main(String[] args) {
        int n = 5;
        int m = 5;
        for (int i = 1; i <= n; i++) {

            for (int j = 1; j <= m-i+1; j++) {
                System.out.print(" ");
            }
            for (int j = 1; j <= m; j++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

Is there any other way to print same Star-pattern using only for-loop with less statements in Java?

3

There are 3 best solutions below

0
Sam On

Something like this would do it:

for (int i = 5; i > 0; i--) {
    System.out.println(" ".repeat(i) + "*".repeat(5));
}

The repeat method on the String object is "new" since Java 11.

0
Oleg Cherednik On

You do it almost right. Just one tiny mistake in the first loop.

public static void printSolidRhombus(int height, int width) {
    String stars = "*".repeat(width);

    while (height-- > 0) {
        for (int i = 0; i <= height; i++)
            System.out.print(' ');

        System.out.println(stars);
    }
}

When you call printSolidRhombus(5, 7) you get:

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

P.S. I would remove on space column from the patter, to make the last row like *******

0
Andy Turner On

You could do it recursively without any loops:

static void recursive(String prefix, String suffix) {
  System.out.println(prefix + suffix);
  if (prefix.length() > 1) {
    recursive(prefix.substring(1), suffix);
  }
}

public static void main(String[] args) {
  recursive("     ", "*****");
}