Printing *s as triangles in Java?
Hint: For each row, you need to first print some spaces and then print some stars. The number of spaces should decrease by one per row, while the number of stars should increase.
For the centered output, increase the number of stars by two for each row.
Ilmari Karonen has good advice, and I'd just like to generalize it a bit. In general, before you ask "how can I get a computer to do this?" ask "how would I do this?"
So, if someone gave you an empty Word document and asked you to create the triangles, how would you go about doing it? Whatever solution you come up with, it's usually not hard to translate it to Java (or any other programming language). It might not be the best solution, but (hopefully!) it'll work, and it may point you to a better solution.
So for instance, maybe you would say that you'd type out the base, then go up a line, then type the next highest line, etc. That suggests that you can do the same in Java -- create a list of Strings, base-to-top, and then reverse them. That might suggest that you can just create them in reverse order, and then not have to reverse them. And then that might suggest that you don't need the list anymore, since you'll just be creating and printing them out in the same order -- at which point you've come up with essentially Ilmari Karonen's advice.
Or, maybe you'd come up with another way of doing it -- maybe you'd come up with Ilmari Karonen's idea more directly. Regardless, it should help you solve this and many other problems.
package apple;
public class Triangle
{
private static final int row = 3;
public static void main(String...strings){
printLeftTrangle();
System.out.println();
printRightTrangle();
System.out.println();
printTrangle();
}
/* Pattern will be
*
**
***
****
*/
public static void printLeftTrangle(){
for(int y=1;y<=row;y++){
for(int x=1;x<=y;x++)
System.out.print("*");
System.out.println();
}
}
/* Pattern will be
*
**
***
****
*/
public static void printRightTrangle(){
for(int y=1;y<=row;y++){
for(int space=row;space>y;space--)
System.out.print(" ");
for(int x=1;x<=y;x++)
System.out.print("*");
System.out.println();
}
}
/* Pattern will be
*
***
*****
*/
public static void printTrangle(){
for(int y=1, star=1;y<=row;y++,star +=2){
for(int space=row;space>y;space--)
System.out.print(" ");
for(int x=1;x<=star;x++)
System.out.print("*");
System.out.println();
}
}
}