Almost everbody has either done the Factorial program or is almost there. The really tricky part is seeing how using the for loop (or any loop, for that matter) allows you to incrementally solve the problem of calculating the factorial. Here's my take on it.
The factorial of a number is what we get when we multiply all the numbers between 1 and the number together. (We write it as 5! or 4! or whatever.)
5! is 5 * 4 * 3 * 2 * 1 (= 120)
4! is 4 * 3 * 2 * 1 (=24)
3! is 3 * 2 * 1 (=6)
The difficulty (conceptually speaking) is how to implement this relatively simple piece of mathematics in a loop.
Let's look at 4!
4! is 4 * 3 * 2 * 1 and is equal to 24.
Look at the diagram below. Note that going from right to left, the number we are multiplying by increases by 1. That's our loop control variable (which I was calling idx today) because it is always incrementing by a set amount.
In each loop we multiply the product of the previous loop by the current value of the counter. So in loop 3 below we multiply 2 (which was the product from the previous loop) by 3 which is the counter value in loop 3. In loop 4, we multiply that value (6) by the counter value (which is now 4) to get 24. We exit our for loop when the counter reaches the value that we got from the user.
Tomorrow, we'll be looking more closely at Strings and some neat methods we
can use to manipulate them. Read pp 138 and 139 if you get the chance.
The difficulty (conceptually speaking) is how to implement this relatively simple piece of mathematics in a loop.
Let's look at 4!
4! is 4 * 3 * 2 * 1 and is equal to 24.
Look at the diagram below. Note that going from right to left, the number we are multiplying by increases by 1. That's our loop control variable (which I was calling idx today) because it is always incrementing by a set amount.
In each loop we multiply the product of the previous loop by the current value of the counter. So in loop 3 below we multiply 2 (which was the product from the previous loop) by 3 which is the counter value in loop 3. In loop 4, we multiply that value (6) by the counter value (which is now 4) to get 24. We exit our for loop when the counter reaches the value that we got from the user.
Loop 4 * 3 * 2 * 1
2 | | |___|
| | |
3 | 3 * 2
| |_____|
| |
4 4 * 6
|______|
|
24
Tomorrow, we'll be looking more closely at Strings and some neat methods we
can use to manipulate them. Read pp 138 and 139 if you get the chance.
No comments:
Post a Comment