more efficient printTriangle program?
807597Oct 1 2005 — edited Nov 8 2005Hello, How can I efficiently write a java program to draw a triangle with asterisks. For example;
Please enter the triangle width:
5
*
**
***
****
*****
****
***
**
*
The user defined integer is supposed to be the widest part of the triangle (the middle row). Apparently this program can be written in in two loops, on inside the other, but I can't think of any way. Any help is really appreciated. Thank you so much. I have this, which works but it's long:
public class PrintTriangle {
public static void main(String[] args) {
System.out.println("Please enter the triangle width:"); //prompt user
int width = In.getInt(); //get input
// loop width times, one for each row
for (int i = 0; i < width; i++) {
// print j asterisks
for (int j = 0; j < i; j++)
System.out.print("*");
// print width - i spaces
for (int j = 0; j < width - i; j++)
System.out.print("");
// print a new line
System.out.println();
}
// loop width times, one for each row
for (int i = 0; i < width; i++) {
// print j spaces
for (int j = 0; j < i; j++)
System.out.print("");
// print width - i asterisks
for (int j = 0; j < width - i; j++)
System.out.print("*");
// print a new line
System.out.println();
}
}
}