0% found this document useful (0 votes)
4 views

11 Control Statements

Uploaded by

bhavya reddy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

11 Control Statements

Uploaded by

bhavya reddy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

10/8/18

Control Statements
Once upon a time . . .
Jerry Cain
CS 106AJ
October 5, 2018
slides courtesy of Eric Roberts

Holism vs. Reductionism


In his Pulitzer-prizewinning book,
computer scientist Douglas Hofstadter
identifies two concepts—holism and
reductionism—that turn out to be
important as you begin to learn about
programming. Hofstadter explains these
concepts using a dialogue in the style of
Lewis Carroll: Control Statements
Achilles: I will be glad to indulge both of you, if you will first oblige me, by telling
me the meaning of these strange expressions, "holism" and
"reductionism".
Crab: Holism is the most natural thing in the world to grasp. It’s simply the
belief that "the whole is greater than the sum of its parts". No one in his
right mind could reject holism.
Anteater: Reductionism is the most natural thing in the world to grasp. It’s simply
the belief that “a whole can be understood completely if you understand
its parts, and the nature of their 'sum'". No one in her left brain could
reject reductionism.

Statement Types in JavaScript Boolean Expressions


• JavaScript defines two types of operators that work with
• Statements in JavaScript fall into three basic types: Boolean data: relational operators and logical operators.
– Simple statements
• There are six relational operators that compare values of other
– Compound statements
types and produce a true/false result:
– Control statements
= == Equals !== Not equals
• Simple statements are typically assignments, function calls, or < Less than <= Less than or equal to
applications of the ++ or -- operators. Simple statements are Greater than Greater than or equal to
> >=
always terminated with a semicolon.
• Compound statements (also called blocks) are sequences of For example, the expression n <= 10 has the value true if n is
statements enclosed in curly braces. less than or equal to 10 and the value false otherwise.
• There are also three logical operators:
• Control statements fall into two categories:
– Conditional statements that specify some kind of test && Logical AND p && q means both p and q
– Iterative statements that specify repetition || Logical OR p || q means either p or q (or both)
! Logical NOT !p means the opposite of p

1
10/8/18

Notes on the Boolean Operators Short-Circuit Evaluation


• Remember that JavaScript uses = for assignment. To test • JavaScript evaluates the && and || operators using a strategy
whether two values are equal, you must use the = = = operator. called short-circuit mode in which it evaluates the right
• It is not legal in JavaScript to use more than one relational operand only if it needs to do so.
operator in a single comparison. To express the idea • For example, if n is 0, the right operand of && in
embodied in the mathematical expression n !== 0 && x % n === 0
0 ≤ x ≤ 9
is not evaluated at all because n !== 0 is false. Because the
you need to make both comparisons explicit, as in expression
0 <= x && x <= 9 false && anything
• The || operator means either or both, which is not always is always false, the rest of the expression no longer matters.
clear in the English interpretation of or.
• One of the advantages of short-circuit evaluation is that you
• Be careful when you combine the ! operator with && and || can use && and || to prevent errors. If n were 0 in the earlier
because the interpretation often differs from informal English. example, evaluating x % n would result in a division by zero.

The if Statement Functions Involving Control Statements


• The simplest of the control statements is the if statement, • The body of a function can contain statements of any type,
which occurs in two forms. You use the first when you need including control statements. As an example, the following
to perform an operation only if a particular condition is true: function uses an if statement to find the larger of two values:
if (condition) { function max(x, y) {
statements to be executed if the condition is true if (x > y) {
} return x;
} else {
• You use the second form whenever you need to choose return y;
}
between two alternative paths, depending on whether the }
condition is true or false:
if (condition) { • As this example makes clear, return statements can be used
statements to be executed if the condition is true at any point in the function and may appear more than once.
} else {
statements to be executed if the condition is false
}

The switch Statement Example of the switch Statement


JavaScript
If none
When
The of then
evaluates
the
JavaScript
switch looks
values
statement statements
for
in
executes a case
the
provides
provides aain
acase clause
the case
thatmatch
clauses
convenient matches
or default
statement,
convenient
switch syntaxthefor
syntax expression.
clause
expression,
itforbegins
choosingby
choosing The switch statement is useful when a function must choose
until
If expression
it reaches
JavaScript
among ofispossible
aequal
a setexpression.
evaluating evaluates toor
the
break vstatements
2,aJavaScript
paths:returnin statement.
chooses
the the second
default clause.clause. among several cases, as in the following example:
function monthName(month) {
switch ( expression ) { switch (month) {
case v1: case 1: return "January";
case 2: return "February";
statements to be executed if expression is
= equal
v1 to v1 case 3: return "March";
break; case 4: return "April";
case v2: case 5: return "May";
statements to be executed if expression is
= equal
v2 to v2 case 6: return "June";
break; case 7: return "July";
. . . more case clauses if needed . . . case 8: return "August";
default: case 9: return "September";
statements to be executed if no values match case 10: return "October";
case 11: return "November";
break;
case 12: return "December";
} default: return undefined;
}
}

2
10/8/18

The while Statement The digitSum Function


• The while statement is the simplest of JavaScript’s iterative
control statements and has the following form:
while ( condition ) {
statements to be repeated
}
n result
n1729 sum
19
• When JavaScript encounters a while statement, it begins by 1729
172
17
1
0 11
18
19
9
0
evaluating the condition in parentheses.
• If the value of condition is true, JavaScript executes the
statements in the body of the loop.
• At the end of each cycle, JavaScript reevaluates condition to
see whether its value has changed. If condition evaluates to digitSum(1729) = 19

false, JavaScript exits from the loop and continues with the
statement following the end of the while body.

The for Statement Exercise: Reading for Statements


• The for statement in JavaScript is a powerful tool for Describe the effect of each of the following for statements:
specifying the structure of a loop independently from the
operations the loop performs. The syntax looks like this: 1. for (let i = 1; i <= 10; i++)
This statement executes the loop body ten times, with the control
for ( init ; test ; step ) { variable i taking on each successive value between 1 and 10.
statements to be repeated
} 2. for (let i = 0; i < n; i++)
This statement executes the loop body n times, with i counting from
• JavaScript evaluates a for statement as follows: 0 to n-1. This version is the standard Repeat-n-Times idiom.
1. Evaluate init, which typically declares a control variable.
2. Evaluate test and exit from the loop if the value is false. 3. for (let n = 99; n >= 1; n -= 2)

3. Execute the statements in the body of the loop. This statement counts backward from 99 to 1 by twos.
4. Evaluate step, which usually updates the control variable.
4. for (let x = 1; x <= 1024; x *= 2)
5. Return to step 2 to begin the next loop cycle.
This statement executes the loop body with the variable x taking on
successive powers of two from 1 up to 1024.

The factorial Function The factorialTable Function


• The factorial of a number n (which is usually written as n! in
mathematics) is defined to be the product of the integers from
1 up to n. Thus, 5! is equal to 120, which is 1 x 2 x 3 x 4 x 5.
5040
1
• The following function definition uses a for loop to compute
the factorial function:
min max i
n 0 result
7 i 8
0
1
7
6
function fact(n) {
let result = 1; 0
7 5040
120
720
24
1
2
6 1
2
3
4
5
6
7
8
for (let i = 1; i <= n; i++) {
result = result * i; -> factorialTable(0, 7);
} 0! = 1
return result; 1! = 1
} 2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
->

3
10/8/18

Comparing for and while The Checkerboard Program


• The for statement const GWINDOW_WIDTH = 500; /* Width of the graphics window */
const GWINDOW_HEIGHT = 300; /* Height of the graphics window */
for ( init ; test ; step ) { const N_COLUMNS = 8; /* Number of columns */
const N_ROWS = 8; /* Number of rows */
statements to be repeated const SQUARE_SIZE = 35; /* Size of a square in pixels */
}
function Checkerboard() {
let gw = GWindow(GWINDOW_WIDTH, GWINDOW_HEIGHT);
is functionally equivalent to the following code using while: let x0 = (gw.getWidth() - N_COLUMNS * SQUARE_SIZE) / 2;
let y0 = (gw.getHeight() - N_ROWS * SQUARE_SIZE) / 2;

init; for (let i = 0; i < N_ROWS; i++) {


while ( test ) { for (let j = 0; j < N_COLUMNS; j++) {
statements to be repeated let x = x0 + j * SQUARE_SIZE;
let y = y0 + i * SQUARE_SIZE;
step; let sq = GRect(x, y, SQUARE_SIZE, SQUARE_SIZE);
} let filled = (i + j) % 2 !== 0;
sq.setFilled(filled);
• The advantage of the for statement is that everything you }
gw.add(sq);

need to know to understand how many times the loop will run }
is explicitly included in the header line. }

The End

You might also like