# Creating a triangle

I have two implementation which I modified according to my need to create a triangle or a pyramid like this:

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


First way:

int num = 5;
for(int i=0;i<num;i++) {
for(int j=0;j<num-i;j++) {
System.out.print(" ");
}
for(int k=0;k<=i;k++) {
System.out.print((k==0)?"*":"**");
}
System.out.println();
}


Second way:

int num = 5, spaces = num - 1, charData = 2 * num;
String str = String.join("", Collections.nCopies(spaces, " ")) + String.join("", Collections.nCopies(charData, "*"));
for (int i = 0; i < num; i++)
System.out.println(str.substring(i, num + 2*i));


The second way seems shorter than the first one which takes fewer lines of code and fewer loops. I would like to find out which one is shorter and more efficient. Is there any other way the code can become shorter and more efficient with fewer loops?

Unfortunately, usually the more efficient code, the longer it is. Consider this:

public static String getTriangleString(int height) {
if (height < 0) {
throw new IllegalArgumentException("Negative height: " + height);
}

// Find the capacity that does not waste too much space and that can
// accommodate the entire pyramid:
int capacity = height * (height + 1) + height * (height - 1) / 2;
StringBuilder sb = new StringBuilder(Math.max(0, capacity));

for (int y = 0; y < height; ++y) {
for (int x = height - 2 - y; x >= 0; --x) {
sb.append(' ');
}

sb.append('*');

for (int x = 0; x != y; ++x) {
sb.append("**");
}

if (y < height - 1) {
sb.append('\n');
}
}

return sb.toString();
}


The above implementation should (?) be more efficient than both of your versions, and the reason is that the entire pyramid is printed to standard output only once. (Printing goes down the deeps of your OS kernel.)

Hope that

Post scriptum

Generally, I suggest you make clear separation between algorithms and the output routines. In this case, it means it would be better to have two routines: the first computing the triangle and returning it as a string; and another one manipulating it (such as printing to standard output).