0

I want to "transform" recursive code into iterative code. The example is:

 public int CalcTime(double AnnualIncome, int Time, double Value)
 {
     if (AnnualIncome / 12 > Value / Time) 
         return Time;
     else
         return CalcTime(AnnualIncome, Time + 1, Value);
 }

I tried but could not...

Thank you very much!

5
  • Need clarification on "transform" and "example" in your statement above. Do you simply want to restate the example above iteratively, or are you looking for a means of programmatically transforming the sample source code into an iterative example? Commented Nov 6, 2012 at 19:49
  • What's wrong with it how it is? Commented Nov 6, 2012 at 19:50
  • 1
    @woz easy to blow the stack doing that Commented Nov 6, 2012 at 19:51
  • 2
    Side-note: By convention parameters and local variables should start with a lowercase letter. Commented Nov 6, 2012 at 19:55
  • Good point @CodesInChaos; updated my answer to include a best practice version as well as the original direct equivalent. Commented Nov 6, 2012 at 20:11

2 Answers 2

6

Try this:

public int CalcTime(double AnnualIncome, int Time, double Value)
{
    while (AnnualIncome / 12 <= Value / Time) 
    {
        Time++;
    }
    return Time;
}

Also as @CodesInChaos points out in the comments above, best practice dictates lower case variable names:

public int CalcTime(double annualIncome, int time, double value)
{
    while (annualIncome / 12 <= value / time) 
    {
        time++;
    }
    return time;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Looks correct for sane input values. Might differer if AnnualIncome or Value isn't finite or if Time<=0 (a<=b and !(a>b) aren't equivalent). But the correct solution for that is parameter validation.
1

Conversion from recursive to iterative is most easily done by emulating the CPU natural call stack with your own stack. This is valid for problems that are naturally solved with a recursive function. (not saying this is the most correct approach)

In this case, something like this : (please note that i don't expect this code to either compile or to run as it should, it is just an example of how I believe this should be done)

Stack stack;
int time = 1; 
stack.add(time);

while(!stack.isEmpty)
{
   currentTime = stack.pop();

   if(AnnualIncome / 12 > Value / currentTime )
        return currentTime ;
   else
   {
        stack.push(time+1);
   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.