iv.9. Stack Diagrams for Recursive Functions¶

In the previous affiliate we used a stack diagram to represent the land of a plan during a part call. The same kind of diagram tin can brand it easier to interpret a recursive function.

Remember that every time a office gets called information technology creates a new instance that contains the part'southward local variables and parameters.

This figure shows a stack diagram for countdown , called with n = 3 :

image

At that place is 1 instance of master and four instances of countdown , each with a different value for the parameter n . The bottom of the stack, countdown with north = 0 is the base of operations case. Information technology does non brand a recursive call, so in that location are no more than instances of inaugural .

The case of principal is empty because master does non have any parameters or local variables. As an practice, draw a stack diagram for nLines , invoked with the parameter due north = 4.

    Q-1: Refer to the nLines function beneath. It is the same as the nLines function defined on the previous page. How many instances of nLines would in that location be in the stack diagram if we begin with n = 4?

                                        void                  nLines                  (                  int                  n                  )                  {                  if                  (                  n                  >                  0                  )                  {                  cout                  <<                  endl                  ;                  nLines                  (                  due north                  +                  1                  );                  }                  }                
  • 3
  • If nLines could reach its base case, it cannot be done in iii function calls.
  • 4
  • If nLines could reach its base example, it cannot be done in 4 function calls.
  • 5
  • If nLines could accomplish its base example, it could be done in 5 function calls, but does it e'er reach the base case?
  • infinite
  • The nLines function never reaches its base case, so the stack diagram would be infinitely long.

You lot have attempted of activities on this folio