Recursion
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
- Create a console application
- Write code in Main to get a positive integer from the user
- Declare a method called Factorial that takes a single integer parameter and returns an integer as the result.
- 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)
- Add code to Main to pass the number the user entered to the method and print the result to the console.
- Test the program with several values.
Questions
-
How would you do this calculation with a loop instead of a recursive method?
- 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?
- How would you check that a string entered was the correct length, such as a 7 character SID?
- What is the biggest number you can determine a factorial for and still get the answer in an int variable?
- Did you test your code with 0 or a negative number? What would happen in this case and how could you handle it?