right. You can also try and rewrite the code so it will work for negative integers as
well.
Maria: Can we now write a program that checks for prime numbers using wh ile?
Professor: We are running out of time, so you can do th at at home. Here is a possible
solution, but use it on ly after you have tried to do it by yourselves:
var x = prompt("Enter an integer greater than one.");
var counter = 0;
var n = 2;
while (x > n) {
if (x % n == 0) {
counter++;
}
n++;
}
document.write(counter == 0 ? "Prime number." :
"Not a prime number.");
7.3 Desig n a Simple Program
Professor: Understanding how a simple piece of code works is of te n easier than writ-
ing your own program. Before you start, you shall do some planning, which doesn’t
require any specific computer language knowledge at early stages. Recall our fridge
problem where we w rote a list of instructions to be followed in plain English or pseudo
language, which we called an algorithm. We are going to write an algo rithm in pseudo
language for our next problem as well.
The problem is as follows. Write a program that reads some numbers until a zero is
entered, and calcu la te s and w rites to the browser window the arithmetic mean of the
entered numbers. The arithmetic mean is the sum of a sequence of numbers divided
by the number of numbers in the sequence. Can you compose an algorithm?
Maria: Perhaps something like this:
Read numbers until zero is entered.
Count the numbers.
Sum the numbers.
Divide the sum by the count of the numbers.
Write out the result.
Professor: OK, it’s a start. You might have a tiny problem with the implementation,
though. You won’t be able to store the numbers so you can count and sum them later.
Maria: Why is that? I ca n use variables, can’t I?
Professor: Ask you rself some questions. For example: “How many variables do I
need?” Or this one: “How do I tell a program to store each value in its own variable
without making the program unrea sonably long?”
136 Meeting 7. Controlling Program Flow
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
Trying to locate errors in your code is called debugging and a tool that helps you to
do it is called a debugger. T he name stems from the ancient era of computing, when
occasionally real bugs were found to dwell inside a computer. Computers oered them
shelter and plenty of food like crumbs from sandwiches and pizzas, the programmers’
basic nutrition sources. Acids in those bugs’ feces damaged the sensitive electronic
circuits causing har dware failures. Nowadays, a software failure is also called a bug
to honor those first bugs. But that’s just one of the many stories about the etymology
of “computer bug.
The DevTools has integrated debugging tools, a tiny portion of which we’re going to
use now. Press Ctrl+S hift+I to open the DevTools and then select
Sources from
the menu. You should see something like what appears on this screensh ot.
Next, click the disclosure triangle at the left side of the DevTools besid e the 1 27.0.0.1
number. The navigator expands and you select the file in which your code is lo cated.
After you do that, you should see the source code of your program inside the DevTools
window.
What we are going to do now is to pause the program execution at the point we susp ect
is critical and observe the values o f some variables. To do tha t, we need to set a
breakpoint, which is a poin t in the prog ram where the execution will pause. We can set
a breakpoint simply by clicking the number before the line where the program should
pause. I think that line 12 is the most interesting for us so we set a breakpoint to this
line. A dark gray arrow appears to in dicate a break point. To remove a breakpoint,
simply click the arrow and it will disappear.
138 Meeting 7. Controlling Program Flow
Next, we add variables whose values we want to o bserve. Click the plus sign next to
the
Watch Expressions menu item at the right side of the DevTools and enter the name
of the nu mber variable so we can watch its value. By the way, you can in fact watch
any expression here and not just variables.
Now yo u run th e program again by refreshing the browser window (press F5) and
input the number 4 into the prompt. After pressing
OK, you should see the following
situation.
If you watch carefully, you might alrea dy see where the problem is.
Mike: Below the
Watch Expressions item, I notice th at number h as the correct value
but it is in quotes. Does that mean it is a string?
Professor: Precisely. The type of the value that prompt() returns is a string. You
can observe what happens next if yo u execute just the line of the program wh ere the
execution has paused. You do that b y selecting
Step Over (the curved arrow over a
dot above the
Watch Expressions menu item). Alternatively, you can press F10. The
value of sum will also be of interest to us n ow, so let’s add it to the watch expressions
the same way we added number. The situation is as seen on this screenshot.
Notice that as soon as line 12 has been executed, the stripe over the code moves to the
next line, so you always know which line of code will be executed next.
Now that we discovered that prompt() retur ns a string, it comes as no surprise to us
7.3. Design a Simple Program 139
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.19.162