There is A LOT going on in this short piece of code. The essential idea is the
following:
If you have n cents, you could make change for it by doing the following:
1) use a quarter, then count how many ways to change n-25 cents
2) use a dime, then count how many ways to change n-10 cents
3) use a nickel, then count how many ways to change n-5 cents
4) use a penny, then count how many ways to change n-1 cents
But, there’s a problem here – what is it?
So we can take care of this problem with the following stipulations:
1) use a quarter, then count how many ways to change n-25 cents
2) use a dime, then count the ways to change n-10 cents, with dimes or less
3) use a nickel, then count the ways to change n-5 cents, with nickels or less
4) use a penny, then count the ways to change n-1 cents, with pennies or less
Why does this take care of our problem?
Essentially, in our function, we return the number of ways to make change for
cents cents, where den is our largest denomination. THUS, the number of recursive
calls we make DEPENDS on our value of DEN. If DEN=5, then we only need to
make 2 calls, if it’s 10 we need to make 3, etc. The sum of these recursive calls is
the answer to our question.
Notice, how we add the values returned by the appropriate number of recursive
calls using the switch statement WITHOUT breaks. You can certainly implement
this algorithm without a switch statement, but then the code would be slightly more
cumbersome.
Also, we need to take a look at our “base” cases so to speak. A recursive function
CAN NOT call itself always. (Why is this?) So, when the problem is easy enough
to solve on it’s own right, you can just directly solve the problem. In essence, as
was mentioned in CS1, you do one of two things:
1) Solve the problem because it’s simple.