Lab 2 - Intro to Recursion

In this lab, you'll explore the concept of recursion.  Specifically, you'll develop a small console application that invokes a recursive method that will calculate the product of the numbers 1 to n.

The lab will have multiple steps, and you should try and perform the lab steps on your own, but certainly click through the how-to links to see step-by-step walkthroughs on how to complete each step.

Here are the steps:

  1. Write the recursive method
  2. Invoke the method from within main and display the results
  3. Utilize breakpoints to explore how the activation stack works

Step 1 - Writing the Recursive Method

Note that the product of the numbers 1 to n can be written as follows

Product(n) = 1 * 2 * 3 * ... * (n-2) * (n-1) * n

We can reverse this formula to write it as

Product(n) = n * (n-1) * (n-2) * ... * 3 * 2 * 1

And we can further state that

Product(1) = 1

Notice this gives us our terminating case.

Now, we can rewrite the formula recursively as

Product(n) = n * Produc(n-1)
Product(1) = 1

Given the above, write a recursive method that takes in an integer (n) and returns an integer that represent the product of the numbers 1 to n.

Click this how-to to see a step-by-step solution for this part of the lab.


Step 2 - Writing Main

Now that you've written the recursive method Product, we'd like to make use of it.

Simply prompt the user, declare a variable, read in an int from the user, invoke the method, and store the result of the method's invocation.  Then print out this result.

Click this how-to to see a step-by-step solution for this part of the lab.


Step 3 - Using breakpoints and tracing execution

In the steps above, you wrote the method and then wrote the code for main to invoke the method and display the results.  Now, let's examine what's REALLY going on as this method works.  To do this, we can place a breakpoint in the method's code and then the program will halt/pause whenever the program execution gets to that line of code.

Insert a breakpoint on the "if" conditional expression within the Product method.  This is line 11 in my sample code.  Then run the program (in Debug mode using "F5") and notice how the call stack is working.  Step line-by-line to see how the control flow of the program works.

Click this how-to to see a step-by-step solution for this part of the lab.


Wrapping it all up

Click her to see the finished ZIPed solution.