These are questions indica ting problems very similar to those connected with yo ur
prime numbers homework. The story is repeating itself: the more numbers you want
to include in the calculation the longer you r program will be. Unfortunately, you
cannot solve this pro blem using just variables of primitive data types.
Maria: I see. Does that mean we have to wait until we learn mor e?
Professor: Not necessarily. You ca n rewrite the first three lines so that individual
numbers are not stored. There’s really no need for storing them.
Maria: OK
...? Oh yes, now I see a solutio n. I will count and sum the n umbers on the
fly, which means I don’t have to store them individually. Perhaps some thing like this:
Set counter and sum to zero.
Repeat:
Read number. If it is zero, stop repeating.
Add number to sum.
Increment counter by on e.
End Repeat
Divide sum by counter.
Write out the result.
Professor: Brilliant! The next step is to code the algorithm in JavaScript. That should
be fairly easy now.
Mike: I will try:
var counter = 0, sum = 0;
var number, mean;
while (number = prompt("Enter a number:")) {
sum += number;
counter++;
}
mean = sum / counter;
document.write(mean);
Professor: I like how you used the fact that the assignment operator returns the value
assigned to number. In y our case, wh en a falsy value is returned by prompt(), the
while lo op will stop .
The last step in program development is testing. Basically, testing is executing a
progr am with th e purpose of fin ding errors in it. The re’s quite som e th eory behind it,
but we’ll just use some investigative intuitio n with a little help of the DevTools.
When you start y our program and enter some numbers, for example, four, five, six,
and ze ro, you notice th at the loop doesn’t stop but the prompt opens once again. Now
you hit
Cancel and the page loads and you see the nu mber 1140 written on it. It is
next to im possible to figure out what happened without a proper tool.
7.3. Design a Simple Program 137