satheesh
satheesh

Reputation: 137

How to exit from recursive call?

I have following code for recursive call.

public string success() 
{
  string status = RecursiveMethod();
  return status;
}

 public string RecursiveMethod()
 {
   string response = "fail";
   if (response =="fail")
   {
     RecursiveMethod();
   }
   return response;
 }

The above code working correctly if the response is fail. After the three consecutive fail i changed the response value fail to success. In this the RecursiveMethod function execute three times and it will exit from the loop with fail response. what is the problem in it. In my case if the response is success it will exit from the control. can any one try to help me.

Upvotes: 0

Views: 520

Answers (3)

anders stubberup
anders stubberup

Reputation: 544

Add a parameter to the method that is a Int (or a smaller datatype like a short or byte) with the default as 3 and every time it calls itself it should call with the value minus one.

public string success() 
{
    string status = RecursiveMethod();
    return status;
}

public string RecursiveMethod(int count = 3)
{
    string response = "fail";
    if (response =="fail" && count > 0)
    {
        RecursiveMethod(--count);
    }
    return response;
}

Upvotes: 1

Sibgath
Sibgath

Reputation: 90

Update your code as below and write logic in CheckStatus which will return fail or success

public string success() 
{
  string status = RecursiveMethod();
  return status;
}

 public string RecursiveMethod()
 {
   string response = CheckStatus();
   if (response =="fail")
   {
     RecursiveMethod();
   }
   return response;
 }

string CheckStatus()
{
    //Write Logic on which return "success" or "fail"
}

Upvotes: 0

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56697

Well, it is not clear from your code where the response actually comes from. I'd refactor this to:

public string RecursiveMethod()
{
    string response = "fail";

    if (someOtherConditionApplies)
        response = "success";

    if (response == "fail")
    {
        response = RecursiveMethod();
    }

    return response;
}

You somewhere have to make sure that you

  1. exit the recursion
  2. use the result of the recursive call

The question to me, however, is: Why do you use recursion in this case at all?

Upvotes: 1

Related Questions