user1673123
user1673123

Reputation: 31

How can I exit from a recursive function?

I am working on a program which works with a recursive function.

My problem is when the work of the recursive function is complete, and control is transferred to next function, it returns back to recursive function after completing work of next function.

I need some code which could force from control being transferred back to function. I don't want to exit my program.

public void function1(a, num)
{
  if(a >= num)
  {
    if(a > num)
      function1(a, num);
    else if(a == num)
    {
      a++;
      function1(a, num)
    }
  }
  else
    function2(a, num)
}

public void function2(a, num)
{
  //print result;
}

Every time I'm calling function1, I'm performing some changes in variables a and num. But the problem is that at certain condition when function2 is called control is passed to function1 again. Could you provide me with some code to prevent that? It is a section of a time table generator I'm designing.

Upvotes: 3

Views: 15096

Answers (4)

U1199880
U1199880

Reputation: 905

Perhaps the code would be simpler if you just performed a straight loop.

while (a <= num)
{
   function2(a, num);
   a++;
}

Upvotes: 0

Louis Kottmann
Louis Kottmann

Reputation: 16648

You need to change it to:

public void function1(a,num)
{
    if(a>num)
     {
       //Increment num or decrease a here, otherwise the recursion never ends
       function1(a,num);
       return; //Each time the method does a recursion, it stops to execute itself with
       // a new set of arguments, but when one of them decide it's over, all the 
       // instances of the method will resume one by one, so if you don't return, 
       // it executes the rest of function1.
     }
    else if(a==num) 
     {
       a++; //You probably don't want to do that, this a==num case should be merged
       // with a>num. Can you see why?
       function1(a,num)
       return;
     }
    else
       function2(a,num)
}

public void function2(a,num)
{
 //print result;
}

Upvotes: 1

Krzysztof Jabłoński
Krzysztof Jabłoński

Reputation: 1941

This version of your function works exactly the same.

public void function1(a, num)
{
    if (a < num)
    {
        function2(a, num);
    }
    else
    {
        function1((a > num) ? a : a + 1, num);
    }
}

public void function2(a, num)
{
    //print result;
}

Just for your information: if a is passed, that is greater than num, then the function will recurse ininitely, with efective call of the same argument list function1(a, num), thus it'll never return resulting in hangup and eventually a stack overflow at some point.

Upvotes: 2

Raghuveer
Raghuveer

Reputation: 2637

Put a return whenever you want to return to base

Upvotes: 3

Related Questions