Here is how I can write it.
// three loops public static void stars(int size) { for (int y = 0; y < size; y++) { for (int i = 0; i < y && i < size - y - 1; i++) System.out.print(' '); for (int i = Math.min(y, size - y - 1); i < Math.max(y + 1, size - y); i++) System.out.print('*'); System.out.println(); } }
or
// two loops public static void stars(int size) { for (int y = 0; y < size; y++) { for (int x = 0; x < size; x++) System.out.print( (x >= y && x < size - y) || (x >= size - y - 1 && x <= y) ? '*' : ' '); System.out.println(); } }
or
// one loop public static void stars(int size) { for (int i = 0; i < size * size; i++) { int y = i / size, x = i % size; System.out.print( (x >= y && x < size - y) || (x >= size - y - 1 && x <= y) ? '*' : ' '); if (x == size - 1) System.out.println(); } }
Note. Whether it uses one, two or three cycles, the time complexity is O (N ^ 2). A simple way to determine this is by the number of stars O (N ^ 2) produced, regardless of how this is done.
Peter Lawrey
source share