0% found this document useful (0 votes)
7 views64 pages

JavaScript Control Statements Overview

Uploaded by

tejathella2000
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views64 pages

JavaScript Control Statements Overview

Uploaded by

tejathella2000
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

JavaScript: Control Statements II

• Introduction
• Essentials of Counter-Controlled Repetition
• for Repetition Statement

• Examples Using the for Statement


• switch Multiple-Selection Statement

• do while Repetition Statement

• break and continue Statements

• Labeled break and continue Statements


• Logical Operators
Introduction

• The techniques you will learn here are


applicable to most high-level languages,
including JavaScript.
Essentials of Counter-Controlled Repetition

• Counter-controlled repetition requires


1. Name of a control variable
2. Initial value of the control variable
3. The increment (or decrement) by which the
control variable is modified each time
through the loop
4. The condition that tests for the final value of
the control variable to determine whether
looping should continue
Essentials of Counter-Controlled Repetition

• The double-quote character delimits the


beginning and end of a string literal in
JavaScript
– it cannot be used in a string unless it is
preceded by a \ to create the escape
sequence \”
• XHTML allows either single quotes (') or
double quotes (") to be placed around the
value specified for an attribute
• JavaScript allows single quotes to be placed in
a string literal
1 <?xml version = "1.0" encoding = "utf-8"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "[Link]
4
5 <!-- Fig. 8.1: [Link] -->
6 <!-- Counter-controlled repetition. -->
7 <html xmlns = "[Link]
8 <head>
9 <title>Counter-Controlled Repetition</title>
10 <script type = "text/javascript">
11 <!--
12 var counter = 1; // initialization
13
14 while ( counter <= 7 ) // repetition condition
15 {
16 [Link]( "<p style = \"font-size: " +
17 counter + "ex\">XHTML font size " + counter +
18 "ex</p>" );
19 ++counter; // increment
20 } //end while
21 // -->
22 </script>
23 </head><body></body>
24 </html>
for Repetition Statement

 for repetition statement


 Handles all the details of counter-controlled

repetition
 for structure header
for Repetition Statement
• for statement
– Cpecifies each of the items needed for counter-controlled repetition with a control variable
– Can use a block to put multiple statements into the body
• If the loop’s condition uses a < or > instead of a <= or >=, or vice-
versa, it can result in an off-by-one error
• for statement takes three expressions
– Initialization
– Condition
– Increment Expression
• The increment expression in the for statement acts like a stand-
alone statement at the end of the body of the for statement
• Place only expressions involving the control variable in the
initialization and increment sections of a for statement
for Repetition Statement
• The three expressions in the for statement are
optional
• The two semicolons in the for statement are
required
• The initialization, loop-continuation condition and
increment portions of a for statement can
contain arithmetic expressions
for Repetition Statement
for Final value of control variable
Control variable name
keyword for which the condition is
true
for ( var counter = 1; counter <= 7; ++counter
)
Initial value of control variable Increment of control variable
Loop-continuation condition

Fig. 9.3 for statement header


components.
for Repetition Statement
• The part of a script in which a variable name can be
used is known as the variable’s scope
• The “increment” of a for statement may be negative, in
which case it is called a decrement and the loop actually
counts downward
• If the loop-continuation condition initially is false, the
body of the for statement is not performed
– Execution proceeds with the statement following the for
statement
for Repetition Statement
Establish
initial value
of control
variable.
var counter = 1

[Link](
true "<p style=\"font-size: "
counter <= 7 ++counter
+ counter +
Increment
"ex\">XHTML font size " +
counter + "ex</p>" ); the control
false variable.
Determine Body of loop
if final value (this may be many
of control statements)
variable
has been
reached.

Fig. 9.4 for repetition structure


flowchart.
Examples Using the for Statement

• JavaScript does not include an


exponentiation operator
– Math object’s pow method for this purpose.
[Link](x, y) calculates the value of x
raised to the yth power.
• Floating-point numbers can cause trouble
as a result of rounding errors
1 <?xml version = "1.0" encoding = "utf-8"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "[Link]
4
5 <!-- Fig. 8.5: [Link] -->
6 <!-- Summation with the for repetition structure. -->
7 <html xmlns = "[Link]
8 <head>
9 <title>Sum the Even Integers from 2 to 100</title>
10 <script type = "text/javascript">
11 <!--
12 var sum = 0;
13
14 for ( var number = 2; number <= 100; number += 2 )
15 sum += number;
16
17 [Link]( "The sum of the even integers " +
18 "from 2 to 100 is " + sum );
19 // -->
20 </script>
21 </head><body></body>
22 </html>
1 <?xml version = "1.0" encoding = "utf-8"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "[Link]
4
5 <!-- Fig. 8.6: [Link] -->
6 <!-- Compound interest calculation with a for loop. -->
7 <html xmlns = "[Link]
8 <head>
9 <title>Calculating Compound Interest</title>
10 <style type = "text/css">
11 table { width: 100% }
12 th { text-align: left }
13 </style>
14 <script type = "text/javascript">
15 <!--
16 var amount; // current amount of money
17 var principal = 1000.0; // principal amount
18 var rate = .05; // interest rate
19
20 [Link](
21 "<table border = \"1\">" ); // begin the table
22 [Link](
23 "<caption>Calculating Compound Interest</caption>" );
24 [Link](
25 "<thead><tr><th>Year</th>" ); // year column heading
26 [Link](
27 "<th>Amount on deposit</th>" ); // amount column heading
28 [Link]( "</tr></thead><tbody>" );
29
30 // output a table row for each year
31 for ( var year = 1; year <= 10; ++year )
32 {
33 amount = principal * [Link]( 1.0 + rate, year );
34 [Link]( "<tr><td>" + year +
35 "</td><td>" + [Link](2) +
36 "</td></tr>" );
37 } //end for
38
39 [Link]( "</tbody></table>" );
40 // -->
41 </script>
42 </head><body></body>
43 </html>
switch Multiple-Selection Statement

Controlling expression
Case labels
Default case
switch Multiple-Selection Statement

• switch multiple-selection statement


– Tests a variable or expression separately for each of
the values it may assume
– Different actions are taken for each value
• CSS property list-style-type
– Allows you to set the numbering system for a list
– Possible values include
• decimal (numbers—the default)
• lower-roman (lowercase roman numerals)
• upper-roman (uppercase roman numerals)
• lower-alpha (lowercase letters)
• upper-alpha (uppercase letters)
• others
switch Multiple-Selection Statement
• switch statement
– Consists of a series of case labels and an optional default
case
– When control reaches a switch statement
• The script evaluates the controlling expression in the parentheses
• Compares this value with the value in each of the case labels
• If the comparison evaluates to true, the statements after the case
label are executed in order until a break statement is reached
• The break statement is used as the last
statement in each case to exit the switch
statement immediately
• The default case allows you to specify a set of
statements to execute if no other case is
satisfied
– Usually the last case in the switch statement
switch Multiple-Selection Statement

• Each case can have multiple actions (statements)


• Braces are not required around multiple actions in a
case of a switch
• The break statement is not required for the last case
because program control automatically continues with
the next statement after the switch
• Having several case labels listed together (e.g., case
1: case 2: with no statements between the cases)
executes the same set of actions for each case
1 <?xml version = "1.0" encoding = "utf-8"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "[Link]
4
5 <!-- Fig. 8.7: [Link] -->
6 <!-- Using the switch multiple-selection statement. -->
7 <html xmlns = "[Link]
8 <head>
9 <title>Switching between XHTML List Formats</title>
10 <script type = "text/javascript">
11 <!--
12 var choice; // user’s choice
13 var startTag; // starting list item tag
14 var endTag; // ending list item tag
15 var validInput = true; // indicates if input is valid
16 var listType; // type of list as a string
17
18 choice = [Link]( "Select a list style:\n" +
19 "1 (numbered), 2 (lettered), 3 (roman)", "1" );
20
21 switch ( choice )
22 {
23 case "1":
24 startTag = "<ol>";
25 endTag = "</ol>";
26 listType = "<h1>Numbered List</h1>";
27 break;
28 case "2":
29 startTag = "<ol style = \"list-style-type: upper-alpha\">";
30 endTag = "</ol>";
31 listType = "<h1>Lettered List</h1>";
32 break;
33 case "3":
34 startTag = "<ol style = \"list-style-type: upper-roman\">";
35 endTag = "</ol>";
36 listType = "<h1>Roman Numbered List</h1>";
37 break;
38 default:
39 validInput = false;
40 } //end switch
41
42 if ( validInput == true )
43 {
44 [Link]( listType + startTag );
45
46 for ( var i = 1; i <= 3; ++i )
47 [Link]( "<li>List item " + i + "</li>" );
48
49 [Link]( endTag );
50 } //end if
51 else
52 [Link]( "Invalid choice: " + choice );
53 // -->
54 </script>
55 </head>
56 <body>
57 <p>Click Refresh (or Reload) to run the script again</p>
58 </body>
59 </html>
Fig. 8.7 | Using the switch multiple-selection
statement (Part 3 of 4).
Fig. 8.7 | Using theswitch

multiple-selection
statement (Part 4 of 4).
switch Multiple-Selection Statement
true
case case a break
a action(s)
false

true
case case b break
b action(s)
false

.
.
.

true
case case z break
z action(s)
false

default
action(s)
do…while Repetition Statement

Similar to the while statement


Tests the loop continuation condition after
the loop body executes
Loop body always executes at least once
1 <?xml version = "1.0" encoding = "utf-8"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "[Link]
4
5 <!-- Fig. 8.9: [Link] -->
6 <!-- Using the do...while repetition statement. -->
7 <html xmlns = "[Link]
8 <head>
9 <title>Using the do...while Repetition Statement</title>
10 <script type = "text/javascript">
11 <!--
12 var counter = 1;
13
14 do {
15 [Link]( "<h" + counter + ">This is " +
16 "an h" + counter + " level head" + "</h" +
17 counter + ">" );
18 ++counter;
19 } while ( counter <= 6 );
20 // -->
21 </script>
22
23 </head><body></body>
24 </html>
do…while Repetition Structure

action(s)

true
condition

false

Fig. 9.10 do…while repetition statement


flowchart.
General Format of do…while

initialization;  While
do { initialization;
statement;
while
(loopContiu
increment; ationTest)
} while {
(loopCo increment;
ntiuation
Test); statement;
}
break and continue Statements

 break
 Immediate exit from the structure

 Used to escape early from a loop

 Skip the remainder of a switch statement

 continue
 Skips the remaining statements in the body of

the structure
 Proceeds with the next iteration of the loop
1 <?xml version = "1.0" encoding = "utf-8"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "[Link]
4
5 <!-- Fig. 8.11: [Link] -->
6 <!-- Using the break statement in a for statement. -->
7 <html xmlns = "[Link]
8 <head>
9 <title>
10 Using the break Statement in a for Statement
11 </title>
12 <script type = "text/javascript">
13 <!--
14 for ( var count = 1; count <= 10; ++count )
15 {
16 if ( count == 5 )
17 break; // break loop only if count == 5
18
19 [Link]( "Count is: " + count + "<br />" );
20 } //end for
21
22 [Link](
23 "Broke out of loop at count = " + count );
24 // -->
25 </script>
26 </head><body></body>
27 </html>
1 <?xml ver si on = "1. 0" encodi ng = "ut f - 8"?>
2 <! DOCTYPE ht ml PUBLI C "- / / W3C/ / DTD XHTML 1. 0 St r i ct / / EN"
3 "ht t p: / / www. w3. or g/ TR/ xht ml 1/ DTD/ xht ml 1- st r i ct . dt d">
4
5 <! - - Fi g. 8. 12: Cont i nueTest . ht ml - - >
6 <! - - Usi ng t he cont i nue st at ement i n a f or st at ement . - - >
7 <ht ml xml ns = "ht t p: / / www. w3. org/ 1999/ xht ml ">
8 <head>
9 <t i t l e>
10 Usi ng t he cont i nue St at ement i n a f or St at ement
11 </ t i t l e>
12
13 <scr i pt t ype = "t ext / j avascr i pt ">
14 <! - -
15 f or ( var count = 1; count <= 10; ++count )
16 {
17 i f ( count == 5 )
18 cont i nue; / / ski p r emai ni ng l oop code onl y i f count == 5
19
20 document . wr i tel n( "Count i s: " + count + "<br / >" ) ;
21 } / / end f or
22
23 document . wr i tel n( "Used cont i nue t o ski p pr i nt i ng 5" ) ;
24 // -->
25 </ scr i pt >
26
27 </ head><body></ body>
28 </ ht ml >
Labeled break and continue Statements
 Labeled break statement
 Break out of a nested set of structures
 Immediate exit from that structure and enclosing

repetition structures
 Execution resumes with first statement after enclosing

labeled statement
 Labeled continue statement
 Skips the remaining statements in structure’s body
and enclosing repetition structures
 Proceeds with next iteration of enclosing labeled

repetition structure
 Loop-continuation test evaluates immediately after

the
continue statement executes
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "[Link]
4
<!-- Fig. 9.13: [Link] -->
5
<!-- Using the break statement with a Label -->
6
7
<html xmlns = "[Link]
8
<head>
9
<title>Using the break Statement with a Label</title>
10
11
<script type = "text/javascript">
12
<!--
13
stop: { // labeled block
14
for ( var row = 1; row <= 10; ++row ) {
15
for ( var column = 1; column <= 5 ; ++column ) {
16
17
if ( row == 5 )
18
break stop; // jump to end of stop block
19
20
[Link]( "* " );
21
}
22
23
[Link]( "<br />" );
24
}
25
26
// the following line is skipped
27
[Link]( "This line should not print" );
28
}
29
30
[Link]( "End of script" );
31
// -->
32
</script>
33
34
</head><body></body>
35
</html>
36
Labeled break and continue Statements

• Labeled continue statement


– When executed in a repetition statement (while, for or do…while),
skips the remaining statements in the structure’s body and any number
of enclosing repetition statements
– Proceeds with the next iteration of the specified labeled repetition
statement (a repetition statement preceded by a label)
– In labeled while and do…while statements, the loop-continuation test
evaluates immediately after the continue statement executes
– In a labeled for statement, the increment expression executes, then
the loop-continuation test evaluates
1 <?xml version = "1.0" encoding = "utf-8"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "[Link]
4
5 <!-- Fig. 8.14: [Link] -->
6 <!-- Labeled continue statement in a nested for statement. -->
7 <html xmlns = "[Link]
8 <head>
9 <title>Using the continue Statement with a Label</title>
10 <script type = "text/javascript">
11 <!--
12 nextRow: // target label of continue statement
13 for ( var row = 1; row <= 5; ++row )
14 {
15 [Link]( "<br />" );
16
17 for ( var column = 1; column <= 10; ++column )
18 {
19 if ( column > row )
20 continue nextRow; // next iteration of labeled loop
21
22 [Link]( "* " );
23 } //end for
24 } //end for
25 // -->
26 </script>
27 </head><body></body>
28 </html>
Logical Operators
• Logical operators can be used to form complex
conditions by combining simple conditions
– && (logical AND)
– || (logical OR)
– ! (logical NOT, also called logical negation)
• The && operator is used to ensure that two conditions
are both true before choosing a certain path of execution
• JavaScript evaluates to false or true all expressions
that include relational operators, equality operators
and/or logical operators
Logical Operators

More logical operators


 Logical AND ( && )
 Logical OR ( || )
 Logical NOT ( ! )
Logical Operators (Cont.)

• The && operator has a higher precedence


than the || operator
• Both operators associate from left to right.
• An expression containing && or ||
operators is evaluated only until truth or
falsity is known
– This is called short-circuit evaluation
Logical Operators

expression1 expression2 expression1 &&


expression2
false false false
false true false
true false false
true true true
Fig. 9.15 Truth table for the && (logical
AND) operator.
Logical Operators
• The || (logical OR) operator is used to ensure that
either or both of two conditions are true before
choosing choose a certain path of execution
• ! (logical negation) operator
– reverses the meaning of a condition (i.e., a true
value becomes false, and a false value becomes
true)
– Has only a single condition as an operand (i.e., it
is a unary operator)
– Placed before a condition to evaluate to true if
the original condition (without the logical negation
operator) is false
Logical Operators
expression1 expression2 expression1 ||
expression2
false false false
false true true
true false true
true true true
Fig. 9.16 Truth table for the || (logical OR) operator.

expression !expression
false true
true false
Fig. 9.17 Truth table for operator ! (logical negation).
Logical Operators
• Most nonboolean values can be converted to a boolean
true or false value
• Nonzero numeric values are considered to be true
• The numeric value zero is considered to be false
• Any string that contains characters is considered to be
true
• The empty string is considered to be false
• The value null and variables that have been declared
but not initialized are considered to be false
• All objects are considered to be true
1 <?xml version = "1.0" encoding = "utf-8"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "[Link]
4
5 <!-- Fig. 8.18: [Link] -->
6 <!-- Demonstrating logical operators. -->
7 <html xmlns = "[Link]
8 <head>
9 <title>Demonstrating the Logical Operators</title>
10 <style type = "text/css">
11 table { width: 100% }
12 [Link] { width: 25% }
13 </style>
14 <script type = "text/javascript">
15 <!--
16 [Link](
17 "<table border = \"1\"" );
18 [Link](
19 "<caption>Demonstrating Logical " +
20 "Operators</caption>" );
21 [Link](
22 "<tr><td class = \"left\">Logical AND (&&)</td>" +
23 "<td>false && false: " + ( false && false ) +
24 "<br />false && true: " + ( false && true ) +
25 "<br />true && false: " + ( true && false ) +
26 "<br />true && true: " + ( true && true ) +
27 "</td></tr>" );
28 [Link](
29 "<tr><td class = \"left\">Logical OR (||)</td>" +
30 "<td>false || false: " + ( false || false ) +
31 "<br />false || true: " + ( false || true ) +
32 "<br />true || false: " + ( true || false ) +
33 "<br />true || true: " + ( true || true ) +
34 "</td></tr>" );
35 [Link](
36 "<tr><td class = \"left\">Logical NOT (!)</td>" +
37 "<td>!false: " + ( !false ) +
38 "<br />!true: " + ( !true ) + "</td></tr>" );
39 [Link]( "</table>" );
40 // -->
41 </script>
42 </head><body></body>
43 </html>
Logical Operators
Operator Associativity Type
++ -- ! right to left unary
* % left to right multiplicative
+ - left to right additive
< <= > >= left to right relational
== != left to right equality
&& left to right logical AND
|| left to right logical OR
?: right to left conditional
= += -= *= /= %= right to left assignment
Fig. 9.19 Precedence and associativity of the operators
discussed so far.
Summary of Structured Programming

Flowcharts
 Reveal the structured nature of programs
Single-entry/single-exit control structures
 Only one way to enter and one way to exit each
control structure
Control structure stacking
 The exit point of one control structure is
connected to the entry point of the next control
structure
Single-entry/single-exit sequence, selection
and repetition structures
Summary of Structured Programming

Rules for Forming Structured Programs


1) Begin with the “simplest flowchart” (Fig. 9.22).
2) Any rectangle (action) can be replaced by two rectangles (actions) in sequence.
3) Any rectangle (action) can be replaced by any control structure (sequence, if, if…else, switch,
while, do…while or for).
4) Rules 2 and 3 may be applied as often as you like and in any order.
Fig. 9.21 Rules for forming structured programs.
Summary of Structured Programming

Fig. 9.22 Simplest flowchart.


Summary of Structured Programming

Rule Rule Rule


2 2 2

.
.
.

Fig. 9.23 Repeatedly applying rule 2 of Fig. 9.21 to the simplest flowchart.
Summary of Structured Programming
Rule
3

Rule
3

Applying Rule 3 to the simplest flowchart


Summary of Structured Programming
Stacked building blocks Nested building blocks

Overlapping building blocks


(Illegal in structured programs)

Fig. 9.25 Stacked, nested and overlapped building blocks.


Summary of Structured Programming

Fig. 9.26 Unstructured flowchart.

You might also like