Skip to content
June 26, 2009 / kiranpatils

How to Break Recursive function?

Challenge:

I have one Recursive function which  should check for some condition if it matches then return true. But after match what it does it calls itself from last call stack. Means

Call 1

Recursive Call1 — -Here condition matches and i say retrun true; //expected result is it should stop executing the function. But it calls last Call 1 from Call stack — This is what i understood from the Web resources…some one can correct me if i am wrong🙂

Solution:

Problem is fine but what’s the solution????..Here is the way i did it[Just for demonstration purpose]:

///

/// Counter Variable
///

static int counter = 1;

///

/// IsValid or not flag
/// — Keep it static else it won’t work
///

static bool isValid = false;

private static void MyRecusiveFunction(int p)
{
//RESET STATIC VARIABLE TO FALSE
isValid = false;

//if condition matches
if (counter == 2)
{                
//return true;
//COMMENTED as it was not effective for returning
//Earlier method return type was BOOL now it has
//been replace with void as we can access static
//variable from anywhere
isValid = true;                
}

//if condition not achieved
if (counter < p) { counter++; MyRecusiveFunction(p++); } } [/sourcecode] Basic idea is using static variable and setting it when match found🙂 Links : http://www.c-sharpcorner.com/Forums/ShowMessages.aspx?ThreadID=37288


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: