Java Recursion Triangle Standing on Tip
Posted
by
user1629075
on Stack Overflow
See other posts from Stack Overflow
or by user1629075
Published on 2012-09-19T02:28:32Z
Indexed on
2012/09/19
3:38 UTC
Read the original article
Hit count: 206
I was wondering how to create triangle out of asterisks on its tip rather than on its base.
I have the code for making it stand on its base:
public static String printTriangle (int count)
{
if( count <= 0 ) return "";
String p = printTriangle(count - 1);
p = p + "*";
System.out.print(p);
System.out.print("\n");
return p;
}
But then I'm stuck on how to have the greatest number of stars on the top, and then the next least, and so on. I was thinking something along the terms of having (count - p) to have the input of rows be subtracted from the amount of decrease, but then i was confused by this idea because p is string.
EDIT: I tried changing the position of printTriangle(count - 1) using my original method without iterations and got 1 star per each line; how can I fix this?
public class triangles
{
public static void main(String[] args)
{
printTriangle(5);
}
public static String printTriangle (int count)
{
if( count <= 0 ) return "";
String p = "";
p = p + "*";
System.out.print(p);
System.out.print("\n");
p = printTriangle(count - 1);
return p;
}
}
© Stack Overflow or respective owner