Skip to content
June 26, 2009 / kiranpatils

How to Break Recursive function?


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 🙂


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)
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 :


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: