Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

more efficient printTriangle program?

807597Oct 1 2005 — edited Nov 8 2005
Hello, 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();
}
}
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 6 2005
Added on Oct 1 2005
8 comments
88 views