Home > Software design >  C# - Recursive series
C# - Recursive series

Time:09-18

I have a question in recursion in C#.
My task is to print this:
1 2 3 4 5 @ 10 8 6 4 2 1

I have successfully printed this: 1 2 3 4 5 @ 10 8 6 4 2 0 However, I need to turn the 0 into 1.

This is my code:

public static void Recursive(int a, int b)
        {
            if (a > b)
            {
                Console.WriteLine("@");
                Console.WriteLine(a * 2 - 2);
            }
            else
            {
                Console.WriteLine(a);
                Recursive(a   1, b);
                Console.WriteLine(a*2-2);
            }
        }

CodePudding user response:

It is unclear how your "need turn 0 into 0 (while printing)" is related to recursion, but some basic condition should do - I'd introduce helper method as you seem to need it 3 times:

static void PrintOneInstedOfZero(int v) => Console.WriteLine (v == 0 ? 1 : v);

And use it correspondingly in all 2.5 places (the Console.WriteLine(a*2-2); is repeated twice for no obvious reason, so I count it as 1.5 calls) in your code:

public static void Recursive(int a, int b)
{
    if (a > b)
    {
        Console.WriteLine("@");
        PrintOneInstedOfZero(a * 2 - 2);
    }
    else
    {
        PrintOneInstedOfZero(a);
        Recursive(a   1, b);
        PrintOneInstedOfZero(a * 2 - 2);
    }
}

CodePudding user response:

I have two variants to experiment with:

static void Recursive1(int level)
{
    if (level < 6)
    {
        if (level > 0)
        {
           Console.Write($"{level} ");
        }
        Recursive1(level   1);
        if (level == 0)
        {
           Console.WriteLine("1 ");
        }
        else
        {
           Console.Write($"{2 * level} ");
        }
    }
    else if (level == 6)
    {
        Console.Write("@ ");
    }
}

static void Recursive2(int level)
{
    if (level < 6)
    {
       Console.Write("12345@"[level]   " ");
       Recursive2(level   1);
       Console.Write($"{(level == 0 ? 1 : 2*level)} ");
    }
}

The second variant is probably not what you are supposed to hand in.

  • Related