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]:
/// <summary>
/// Counter Variable
/// </summary>
static int counter = 1;
/// <summary>
/// IsValid or not flag
/// -- Keep it static else it won't work
/// </summary>
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++);
}
}
Basic idea is using static variable and setting it when match found
Links :
http://www.c-sharpcorner.com/Forums/ShowMessages.aspx?ThreadID=37288
