0

There is a recursive function f(). It is looking at cond and then either returning or executing f() then g(). Consider cond to be an external variable that can be set somewhere else, perhaps in a different thread.

  1. If the first five times cond is checked, cond == true, but the sixth time, cond == false, describe the code flow.

  2. Because this is recursive, the code could suffer from a stack overflow if cond == true for too long. Fill in the function iterative_f() so that the code flow is identical to the code flow in (1).

    //recursive
    
    void f()
    {
        if(cond == false)
            return;
        f();
        g();
    }
    
    //iterative  
    void iterative_f() {
    
    }
    
tbag
  • 1,268
  • 2
  • 16
  • 34
  • 1
    So sad to see teachers supplying `boolean_variable == false`! Please use `if (!cond)` or `if (not cond)` (both equivalent and Standard, though I'm not sure if even MSVC++ 2010 supports `not` - think they're too worried about breaking code where people called their variable "not"). – Tony Delroy Apr 08 '11 at 04:23
  • @Tony: `not` is not a C keyword. – JeremyP Apr 08 '11 at 10:47
  • JeremyP: true - C++ only - I should have checked the question's tags :-/. – Tony Delroy Apr 08 '11 at 16:49
  • possible duplicate of [Can every recursion be converted into iteration?](http://stackoverflow.com/q/931762/), [Design patterns for converting recursive algorithms to iterative ones](http://stackoverflow.com/q/1549943/) – outis Jun 20 '12 at 22:41

1 Answers1

4
  1. Since the cond is false the 6th time, the function will in effect execute 5 times. The result is that function g will be executed 5 times.

  2. Now you can write the iterative function as follows:

    void iterative_f() 
    {
       while(cond)
       {
          g();
       } 
    }
Dante May Code
  • 11,177
  • 9
  • 49
  • 81
bala
  • 415
  • 3
  • 13
  • I was asked this in an interview and this was my exact answer. However, the interviewer said that this iterative function would change the sequence in which the function g() gets called. As in the recursive function calls the 5th instance of the function g() first. However, this iterative version would call the 1st instance first. – tbag Apr 08 '11 at 18:48
  • Yes that can be a logical argument. But making a sequence of call to a function cannot have a notion of particular ordering. – bala Apr 09 '11 at 07:04
  • Lets put this in a simpler way. For the recursive function, we are not calling 5th instance of function g() first but we are calling function g() for the first time in the 5th call to function f(). As for the iterative function, we are calling function g() for the first time in the first iteration. Does that make sense? – bala Apr 09 '11 at 07:11