Exercise Recursion C#

Question:

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 that it is 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.

Answer:

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

hacerArbol(int x)

It does not work; but it can be done differently:

string hacerRama(int x, int y)
{
    // Al llegar a x = 1, finaliza la recursividad.
    if (x == 1)
        return string.Concat(Enumerable.Repeat("- ", y - 1)) + '1';

    // La llamada recursiva se hace en hacerRama no en hacerArbol
    return hacerRama(x - 1, y) + Environtment.NewLine + Environtment.NewLine +
           // Cada coleccion de guiones decrece a medida que bajamos ramas
           string.Concat(Enumerable.Repeat("- ", y - x)) +
           // El tamaño de cada rama es una secuencia de numeros impares: 1, 3, 5, 7, 9...
           string.Concat(Enumerable.Repeat(x.ToString() + ' ', (x * 2) - 1));
}

string hacerArbol(int x)
{
    // hacerRama es recursiva
    return hacerRama(x, x);
}

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 hacerRama call at the end of the string.

PS: Starting with two digit numbers doesn't work.

Scroll to Top