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;
}
}
To me it looks like you are missing a loop inside the recursive function to add the correct number on *s for each line.
and calling code to look like
it produces
Also I would use a StringBuilder and not a string for this purpose.
Just reread you question.
in you were after a triangle like this
You need to change when recursion is called.
ie