Lion Blaze
Lion Blaze

Reputation: 11

Recursion error- unreachable

So I am trying to create a simple recursion loop, but I am running into a problem.

After the first return line, it tells me that everything else under it is unreachable, However it needs the first return for recursion to work. What am I doing wrong?

class Program
{
    public static int i = 5;
    static void Main(string[] args)
    {
        name(5);
    }

    public static int name(int i)
    { 
        if (i < 0)
        { }
        return i;
        if (i > 0)
        {
            Console.WriteLine(i);
            i--;
        }
        return i;
    }
}

Upvotes: 0

Views: 104

Answers (3)

Slaven Tojić
Slaven Tojić

Reputation: 3014

Part of your method code is unreachable because you are calling return before it and the method always returns the value at return i so the code after it will never be executed.

if (i < 0)
{ }
return i;//problem here//code after this line gets never executed

And recursive methods are methods that call itself inside the method body, so if you are making a recursive method you probably want something like this:

public static int name(int i)
{
     if (i == 0)
        return i;
     Console.WriteLine(i);
     return name(--i);
}

DEMO HERE

Upvotes: 1

Debashish Saha
Debashish Saha

Reputation: 336

What am I doing wrong? You are returning from a function before the rest of the code block .I feel you should first go through How return works.Anyway just do the following

 if (i < 0)
 {
      return i;
 }

Upvotes: 0

user9726615
user9726615

Reputation:

Quiet simple. You have the first return outside the {} so it occurs to anything that goes through. You want to put it inside the if statement

public static int i = 5;
static void Main(string[] args)
{
    name(5);
}
public static int name(int i)
{
    if (i < 0)
    {
        return i;
    }

    if (i > 0)
    {
        Console.WriteLine(i);
        i--;
    }
    return i;
}

Upvotes: 0

Related Questions