user1659510
user1659510

Reputation: 283

Return Type for recursion in c#

Which return type should we use in c#?Is recursion possible using the "void" return type in c#?

I have a function in which return type is a void, but when I call it, it recursively undergoes Infinite looping, so what is better solution for this:

I am using function as stated below:

void A()
{
  //Some code
  A()
}

Upvotes: 1

Views: 1849

Answers (3)

sudil ravindran pk
sudil ravindran pk

Reputation: 3106

Every recursive method sequence must be somehow terminated. Often the first part of the recursive method will have a branch that tests for a condition being met. In this way, the recursive methods continue until the result is attained. for example

static int Recursive(int value)
    {       
    if (value >= 10)
    {
        // throw new Exception("End");
        return value;
    }
    return Recursive(value + 1);
    }

There is nothing to do with the return type. if conditions are not supplied your function will go to infinite loop

Upvotes: 1

Adriaan Stander
Adriaan Stander

Reputation: 166356

I think your understanding of recursion needs some sharpening.

Have a closer look at Recursion

Despite the usefulness of recursion, you can easily create a recursive function that never returns a result and cannot reach an endpoint. Such a recursion causes the computer to execute an infinite loop.

Another problem that can occur with recursion is that a recursive function can use all the available resources (such as system memory and stack space). Each time a recursive function calls itself (or calls another function that calls the original function), it uses some resources. These resources are freed when the recursive function exits, but a function that has too many levels of recursion may use all the available resources. When this happens, an exception is thrown.

Your issue here is not the return type. You need to have some rule for the resursion to end, lets say a depth of recustion call, or a number of directories as a max to recurs.

Maybe also have a look at Recursive methods using C#

Upvotes: 4

Aditi
Aditi

Reputation: 509

As you are calling the same function, it is obvious it will go in infinite loop. After a condition is satisfied you need to come out of this loop and that can be achieved by using break keyword.

Upvotes: 0

Related Questions