counter = x % 7 == 0 && x != 7 ? counter + 1 : counter;
counter = x % 11 == 0 && x != 11 ? counter + 1 : counter;
counter = x % 13 == 0 && x != 13 ? counter + 1 : counter;
counter = x % 17 == 0 && x != 17 ? counter + 1 : counter;
counter = x % 19 == 0 && x != 19 ? counter + 1 : counter;
document.write(counter == 0 ? "Prime number." :
"Not a prime number.");
The program simply counts the number of tim es the d ivision leaves a remainder of
zero. If there’s no such division, the tested number is a prime nu mber. Of course,
we don’t want to count situations where the number is divided by itself, which also
returns a zero remainder. That’s why we included the inequality comparisons.
Professor: Good. I see that you tested only divisions by prime numbers. There’s
really no need for testing with o ther numbers. For example, if a number is evenly
divisible by four, then it must also be evenly divisible by two. Thus you don’t need
to test the division by four. The same goes for six—if the number is evenly d ivisible
by six, then it must also be evenly divisible by two and three, and there’s no need to
divide by six.
Your program can in fact test the numbers up to 361 because you must only try the
divisions with numbers that are less than o r equal to the square root o f the tested
number. Observe that, if a number n is a product of two positive integers, o nly one
of them can be greater than the square root of n. So, if there existed a divisor greater
than the square root of n, then a divisor smaller than the square root of n would also
exist a nd yo u would already have found it.
Before we start today’s work I want you to understand a fundamental dierence be-
tween the two tasks you had for your homework. The first one could be solved using
a single test, while the second one r equired repeated testing. This ca nnot be done
by simp ly writing many lines of co de because you don’t know how many times the
test should be repeated. This information is not available at the time of writing the
progr am. Besides, just copying and pasting the same code is not programming. For-
tunately, there are tools that allow for automated repetition of tasks, and that’s one of
the top ic s of todays meeting.
Mike: One question: sometimes you write a semicolon at the end of a line and some-
times you don’t. Is there a rule so we know exactly where to put a semicolon? We
experimented and discovered that semicolons are not necessary.
Professor: A semicolon terminate s a statement. Which brings us to another important
topic in JavaScript.
7.2 Statements
Professor: So far we’ve only been working with expressions. Recall that an expres-
sion is evaluated in o rder to return a value. However, technically spea king, you need a
statement in order for that to happen. That is similar to English phrases, which shou ld
be put into sentences. And just as sentences are terminated and separated fro m each
128 Meeting 7. Controlling Program Flow
other with periods, so are stateme nts terminated with semicolons. For example, you
can form a simple statement from an exp ression by adding a semicolon:
expression ;
This kind of statement is called an expression statement. Note that, if expression
has no side eect, such a statement makes no sense. Of course, you can build more
complex statements by combining several subexpressions so that somethin g meaning-
ful happens. For example, to write the value of expression to the browser window,
you can compose a statement like this:
document.write(expression );
A semicolon is important because it makes a statement out of an expression a nd exe-
cutes that statement. It is, however, not necessary to put a semicolon at the end of the
statement if it is the only one, or the la st one on the line. Yet I strongly recommen d
that yo u always termin ate a statement p roperly for consistency.
Flowchart
Professor: Wh en you organize expressions into statements and execute them, the or-
der of execution becomes of paramount importance. So far, execution has simply
followed a list of instructions in the exact order in which they were w ritten. Still,
the conditional operator slightly changed that by evaluating only two of the three ex-
pressions. As we proceed, you’ll see more and more situations wh ere the o rder of
execution is not quite that linear. Esp ecially at the beginning it is useful to have a
graphical tool that will allow you to illuminate what is going on in you r program. The
tool is called a flowchart and it is exactly what it says it is: a ch art wh ic h graphically
represents the flow (o rder) of the statements’ execution.
A flowchar t is composed of two dierent types of boxes depicting two basic types of
actions to be carried out:
A processing step
A decision
A processing step is denoted by a rec ta ngle having an entrance, an exit, and a descrip-
tion of an activity to be accomplished.
Do something
7.2. Statements 12 9
I think the graphics ar e more or less self-explanatory : you follow the arrow enter ing
the box, d o whatever it says should be done inside the box, and, finally, you exit the
box.
A decision is depicted as a diamond with one entrance and two exits.
Condition
true
false
You again start by following th e arrow entering the box. Then you have two possi-
bilities: if the condition inside the box evaluates to true, you exit the box via the
left arrow, and if the condition evaluates to false, you exit the box through the rig ht
arrow.
With dierent combinations of proce ssing and decision boxes, you can assemb le any
algorithm you like.
Maria: We still don’t have repetitions.
Professor: You can connect an arrow exiting a box to the entrance of an arbitrary box.
If one of the arrows exiting a decision box is directed backwards, you get a repetition,
as you will soo n see.
Expression Statement
Professor: As already mentioned, the simplest statement in JavaScript is an expres-
sion that has a side eect terminated with a semicolo n, which is called an expression
statement. For example, if yo u want to increase the value of counter by on e, the next
statement will do it:
counter++; //Increments counter
We can draw a flowchart for this statement, which looks like this.
counter++
Another example of an expression statement is a function call. For examp le :
130 Meeting 7. Contr olling Prog ram Flow
document.write(counter);
Compound Statement
Professor: There are often situations when you need to write several statements while
the rules only allow one . On such occasions you use a compound sta te m ent, which is
no more than a sequence of statements joined into a single one using a pair of curly
brackets. For example:
{
counter++;
x -= counter;
}
Notice that a compound statement doesn ’t end with a semicolon.
Maria: You indented th e lines of code inside the curly brackets. Is this necessary?
Professor: No, it isn’t. Inden ta tion is completely optional, but every programmer
uses it to optically separate statements that are subordinate to another statement. If
the hier archy of statements is clearly visible from the code, the co de is much easier to
read, understand, and, most importantly, main ta in.
The flowchart of the above compound statement looks like this.
counter++
x -= counter
Notice that from the outside , a compound statement looks like a single statement with
a single entran ce and exit, which is indicated by a dashed rectangle.
if/else Conditional
Professor: Apart from expression statem ents, there exists another group of so-called
control state m ents. These statements allow you to change the JavaScript default order
of co de execution, which follows the order in which statemen ts are written.
The if/else statement is the essential control statement that emp owers JavaScript
to make d ecisions. Because this statement actually represents a point in your code
7.2. Statements 13 1
where th e flowchart branches into two paths, it is sometimes known as a “b ranch.
The statement has two forms, the simpler of both having the following syntax:
if (expression ) statement
This statement works as follows. First, expression is evaluated, and if it returns
true, the n statement is executed. Incidentally, st atement is sometimes called a
body of th e i f statement. Otherwise, if expression is false, th en statement is not
executed. For example, the following fragment of code will assign zero to the variable
x if and only if the value of x is null or undefined:
if (x == null) {
x = 0;
}
The code can be illustrated by the following flowchart.
x = 0
x == null
false
true
There are two important aspects I would like to point out regarding this flowchart.
First, notice how the whole if statement only has a single entrance and exit regard-
less of the branch inside. This single e ntrance/exit policy is an important quality of the
structured programming languages to which JavaScript belongs. Second, the expr es-
sion statement x = 0; can be replaced by an arbitrary JavaScript stateme nt, including
empty, compound, o r even another control statement. As a m atter of fact, any rect-
angle inside a ny flowchart can rep resent any JavaScript statement, which is possible
precisely because of a single entrance/exit property of JavaScript statements.
Mike: I’ m a little confused. Why did you use a compound statement composed of
only a single statement?
Professor: I didn’t have to. I could just as well write this code:
if (x == null) x = 0;
132 Meeting 7. Contr olling Prog ram Flow
..................Content has been hidden....................

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