Recursion

Line: Method Line
Medium Difficulty Methods Learning Outcome One Exercise
Type: Exercise
You should have completed:

Method Comments

This topic leads to:

Rectangles

Summary

Methods can be called from other methods in your program, but they can also be called from themselves. This process is called recursion and it can be useful but it is also potentially hazardous. Without careful thought and programming, recursively calling a method can go on forever, or at least until the computer suffers a stack overflow where it runs out of memory for keeping track of where the flow of execution should return to at the end of each method.

The classic example of a use of recursion is in calculating the factorial of a number (n!), defined as

n! = 1 * 2 * 3 * ... * n

From this definition, you may see that n! = n * n-1!

Task

  1. Create a console application
  2. Write code in Main to get a positive integer from the user
  3. Declare a method called Factorial that takes a single integer parameter and returns an integer as the result.
  4. Within that method, implement the following pseudocode design.
    If number is 1
        	return value is 1
    otherwise
           return value is the factorial of (number-1)
  5. Add code to Main to pass the number the user entered to the method and print the result to the console.
  6. Test the program with several values.

Questions

  1. How would you do this calculation with a loop instead of a recursive method?
  2. If the number was out of this range, how could you set it to the nearest valid number? Would it be wise to do so?
  3. How would you check that a string entered was the correct length, such as a 7 character SID?
  4. What is the biggest number you can determine a factorial for and still get the answer in an int variable?
  5. Did you test your code with 0 or a negative number? What would happen in this case and how could you handle it?