How to print hollow diamond pattern in Java

1 Answer

0 votes
public class MyClass {
    public static void print_hollow_diamond_pattern(int rows) {
        // print upper triangle
        for (int i = 1; i <= rows; i++)  {
            for (int j = rows; j > i; j--) {
                System.out.print(" ");
            }
            System.out.print("*"); 
            for (int j = 1; j < (i - 1) * 2; j++) {
                System.out.print(" ");
            }
            if (i == 1) {
                System.out.print("\n");
            }
            else {
                System.out.print("*\n");
            }
        }
        
        // print lower triangle
        for (int i = rows - 1; i >= 1; i--) {
            for (int j = rows; j > i; j--) {
                System.out.print(" ");
            }
            System.out.print("*");
            for (int j = 1; j < (i - 1) * 2; j++) {
                System.out.print(" ");
            }
            if (i == 1) {
                System.out.print("\n");
            }
            else {
                 System.out.print("*\n");
            }
        }
    }
    public static void main(String args[]) {
        print_hollow_diamond_pattern(7);
    }
}



/*
run:

      *
     * *
    *   *
   *     *
  *       *
 *         *
*           *
 *         *
  *       *
   *     *
    *   *
     * *
      *
      
*/

 



answered Sep 30, 2023 by avibootz

Related questions

1 answer 96 views
1 answer 136 views
1 answer 142 views
1 answer 166 views
1 answer 123 views
123 views asked Sep 14, 2023 by avibootz
1 answer 167 views
167 views asked Sep 14, 2023 by avibootz
...