University of Pittsburgh
Summer 2001
CS401:  Introduction to Computer Science
Lab 4:  Writing Recursive Functions in C++
INTRODUCTION

A function is recursive when it is defined in terms of itself (direct-recursion). In other words, somewhere within the body of the function is a call to the same function. To avoid getting stuck in an infinite chain of recursive calls, the definition of a recursive function must provide a special case or cases where no call to the function being defined is made. This special case is called the base case. In addition, each recursive call of the function is made on a "smaller set of arguments" and is assumed to work for such arguments. In other words, the argument, in some sense, is getting "smaller" with each call -- or closer to the base case. When eventually the base case is reached, the recursion stops. Consider, for example, the definition of n-factorial (n!) below:

n! = n * (n-1)!

The definition says that n! is simply the product of n and (n-1)!, assuming (n-1)! produces the correct result. Clearly, without a base case our factorial function would never complete a result. However, we define

0! = 1

as our base case, and the recursion stops when the argument gets to 0. To illustrate, let’s look at 4!:

4! = 4 *( 3!)

= 4 *( 3 * (2!))

= 4 *( 3 *( 2 * (1!)))

= 4 *( 3 *( 2 *( 1 * (0!))))

= 4 *( 3 *( 2 *( 1 * (1))))

= 4 *( 3 *( 2 * (1)))

= 4 *( 3 * (2))

= 4 *( 6)

= 24

Each set of parenthesis represents a recursive call. Note how the final answer is calculated -- the recursive calls continue until the base case is reached. Only then are the actual answers determined, and they are passed "back" to the previous call. Thus, the first result completed is in fact 0!. This result is then used to complete the call for 1! and so on.

When recursion is implemented on a computer, each recursive call is a new, separate execution of the function. When a recursive call is made within a function, the function making the call stops until the recursive call is completed, and then resumes execution. In this way, a recursive function call is just like any other function call. The only difference is that the function is calling itself rather than some other function.
 

OBJECTIVES

In this lab, you will construct a few simple recursive functions in C++ and execute them. This should help you to see how recursion works and to understand what goes on as recursive programs execute.
 
WHAT TO DO

Write a recursive factorial() in C++

Write a C++ program which defines and calls the function fact(n) which is shown below. Your program should have the user input a non-negative long integer, get the factorial by calling the function, then write out the user’s input and the answer in a well-formatted way. 
 
 
// lab 4 - recursive functions
// <your name>
// <today's date>
//

long fact(long);    // prototype

int main() {

   // 
   // you write main()
   //

}

// recursive factorial function
long fact(long n)  {

   if (n == 0)         // base case, 0! = 1
      return 1;
   else
      return (n * fact(n-1));   // recursive call

}
 

Run the program with various inputs. Be sure to try it with a negative input and with a fairly large input (>= 20). Note what happens in each of these cases and think about why it happens. Now put a breakpoint onto the first line in the function body (by moving the cursor to the left of this line and clicking the left mouse). Run the program again. Note that execution will stop when it gets to the line with the breakpoint. Show the call stack by typing CTRL-F3. It should show the initial call of the function. Resume running the program by typing CTRL-F9, and the call stack will change Repeat this procedure until the program is finished executing (use a fairly small value for n so it does not take you all lab). Through the call stack you can see each of the recursive calls, and it is clear here that it is the last call that finishes first. That is why it is called a stack (the last thing you put onto a stack is the first thing you take off).

Print your program to hand in with your worksheet.
 

Another (simple) recursive function

Another simple recursive function, writeout(), is shown below:
 

void writeout(int first, int last)  {
   if (first <= last) {
      cout << " " << first;
      writeout(first + 1, last);
      cout << " " << first;
   }
}

Write a program using this function (using a similar layout as you did in the factorial program earlier), run it and consider its behavior.  Test various calls to this function and watch closely, use the debugger to step through so you can visualize the changes. 

Print this file out as well to turn in with the worksheet. 

 

LOOK IT UP

The call stack you looked at in this lab is a very powerful tool.  Look it up in Borland's help and find out how it can be used to "step back".  That is, pretend you stepped forward by one step accidentally, find out how the call stack can allow to go in "reverse" for a step.