I'm stuck with a recursion exercise in C#, here's the instructions:
-Make a tree as detailed below from the entry of a value of a variable.
Ex: Entry 5
- - - - 1
- - - 2 2 2
- - 3 3 3 3 3
- 4 4 4 4 4 4 4
5 5 5 5 5 5 5 5 5
(I don't know if it looks good, but the idea is to make it in the shape of a triangular pine tree)
If someone could give me a hand to solve it, I would greatly appreciate it, I think there is something in the proposal that I am not being able to reason with.
The code I was able to get is the following:
class Program
{
public class Arbol
{
void hacerArbol(int x)
{
if (x > 0)
{
hacerArbol(x - 1);
if (x < 5)
{
Console.Write("_" + " ");
}
else
{
Console.Write(x);
Console.WriteLine();
}
//hacerArbol(x - 1);
}
}
static void Main(string[] args)
{
Arbol nuevo = new Arbol();
nuevo.hacerArbol(5);
Console.ReadKey();
}
}
}
I cannot manage to pose the figure that is requested, I think there is a part that I cannot imagine how to do.
This recursion exercise seems pretty bad to me... it has the particularity of needing to know the height in advance to be able to write the scripts for each floor, so the function
It does not work; but it can be done differently:
The string resulting from calling
hacerArbol(5)
would be exactly what you put in the example.The trick is to concatenate the strings in reverse by putting the first call to
hacerRama
at the end of the string.PS: Starting with two digit numbers doesn't work.
I don't know if the order of the figure matters, I mean if the pine should be centered or left aligned or something.
But this code has worked for me to solve a left aligned pine tree :)
Its operation is simple.
First two parameters, the first (
max
), the number of iterations that will form the pine tree and the last (color
) which is a default parameter which is 0 (at the first attempt) , with these two, it is drawn along calling itself recursively.With the above code, the following output is produced:
EDIT: Added info.
If you need the tree to be drawn towards the center: Add the following line before the loop
for
:Leaving the code like this:
Which produces the following output:
Something like this might work...
Change the value of the variable
int maxNumberIterate = 5;
and there would be your solved exercise.Code:
https://dotnetfiddle.net/vSs425