xxxxxxxxxx
95
/*
I'm using this brief program to teach while loops.
A separate program teaching for loops will build on this.
*/
/*
Exercise:
How many ways are there to arrange 15 songs
into a playlist?
*/
//Solution: Using a tree, we can see that the answer is
console.log(15 * 14 * 13 * 12 * 11 * 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1);
/*
Exercise:
Typing our solution was repetitive and tedious. If we had
more songs, it would have been more tedious. Other
problems require us to perform the same task 10,000
times or more! Even if the task isn't very hard, that would
take a human a lot of time.
Fortunately, modern computers are extremely fast! So, we want to
tell the computer to take care of repetitive tasks for us.
With the playlist problem, we can do this with a "while loop."
We'll see another way to do it in a later lesson.
So, for this exercise, solve the playlist problem with 15 songs,
using a while loop.
*/
//Solution:
let answer = 1;
let k = 15;
while (k > 0) {
answer *= k;
k--;
}
console.log(answer);
/*
Exercise:
Notice that the number of ways to arrange n
objects is n * (n-1) * ... * 1. We write this as n! and
call it "n factorial."
So, n! = n * (n-1) * ... * 1. Notice that the factors are
in descending order, but n! is also equal to the product of
of the same factors in ascending order: 1 * 2 * ... * n.
For practice, write a while loop that calculates n! using
a product with factors in ascending order.
Does your code produce the same answer to the playlist problem
as before? Check with 15 songs.
Then try it with 20 songs. How many changes did you have to make
so that it would work with 20 songs?
*/
answer = 1;
k = 1;
while (k <= 20) {
answer *= k;
k++;
}
console.log(answer);
/*
Question:
What do you think would happen if we run the following code?
Warning: Don't actually run this code! If you do, then
before you run it, at least make sure to save all work that
you have open on the computer. Also, don't sue me; I
told you not to run it :)
Hint: what's different about the code below and the code
above?
answer = 1;
k = 1;
while (k <= 20) {
answer *= k;
}
console.log(answer);
*/