You are on page 1of 38

JavaScript: Control Statements I

Outline
8.1 8.2 8.3 8.4 8.5 8.6 8.7 8.8 Introduction Algorithms Pseudocode Control Structures if Selection Statement ifelse Selection Statement while Repetition Statement Formulating Algorithms: Case Study 1 (Counter-Controlled Repetition) 8.9 Formulating Algorithms with Top-Down, Stepwise Refinement: Case Study 2 (Sentinel-Controlled Repetition) 8.10 Formulating Algorithms with Top-Down, Stepwise Refinement: Case Study 3 (Nested Control Structures) 8.11 Assignment Operators 8.12 Increment and Decrement Operators 8.13 Note on Data Types 8.14 Web Resources
2004 2003 Prentice Hall, Inc. All rights reserved.

Objectives In this lesson, you will learn:


To understand basic problem-solving techniques. To be able to develop algorithms through the process of top-down, stepwise refinement. To be able to use the if and ifelse selection statements to choose among alternative actions. To be able to use the while repetition statement to execute statements in a script repeatedly. To understand counter-controlled repetition and sentinel-controlled repetition. To be able to use the increment, decrement and assignment operators.

2004 2003 Prentice Hall, Inc. All rights reserved.

8.1 Introduction Writing a script


Thorough understanding of problem Carefully planned approach Understand the types of building blocks that are available Employ proven program-construction principles

2004 2003 Prentice Hall, Inc. All rights reserved.

8.2 Algorithms Actions to be executed Order in which the actions are to be executed

2004 2003 Prentice Hall, Inc. All rights reserved.

8.3 Pseudocode Artificial Informal Helps programmers develop algorithms

2004 2003 Prentice Hall, Inc. All rights reserved.

8.4 Control Structures


Sequential execution
Statements execute in the order they are written

Transfer of control
Next statement to execute may not be the next one in sequence

Three control structures


Sequence structure Selection structure
if ifelse switch

Repetition structure
while dowhile for forin

2004 2003 Prentice Hall, Inc. All rights reserved.

8.4 Control Structures Flowchart


Graphical representation of algorithm or portion of algorithm Flowlines
Indicate the order the actions of the algorithm execute

Rectangle symbol
Indicate any type of action

Oval symbol
A complete algorithm

Small circle symbol


A portion of algorithm

Diamond symbol
Indicates a decision is to be made
2004 2003 Prentice Hall, Inc. All rights reserved.

8.4 Control Structures

add grade to total

total = total + grade;

add 1 to counter

counter = counter + 1;

Fig. 8.1

Flowcharting JavaScripts sequence structure.

2004 2003 Prentice Hall, Inc. All rights reserved.

8.4 Control Structures


JavaScript Keywords break case catch delete do else function if in return switch this typeof var void Keywords that are reserved but not currently used by JavaScript abstract boolean byte const debugger double extends final float import int interface package private protected static super synchronized volatile Fig. 8.2 JavaScript keywords.
2004 2003 Prentice Hall, Inc. All rights reserved.

continue finally instanceof throw while default for new try with

char enum goto long public throws

class export implements native short transient

8.5 if Selection Statement Single-entry/single-exit structure Indicate action only when the condition evaluates to true

2004 2003 Prentice Hall, Inc. All rights reserved.

8.5 if Selection Statement

grade >= 60

true

print Passed

false

Fig. 8.3

Flowcharting the single-selection if statement.

2004 2003 Prentice Hall, Inc. All rights reserved.

8.6 ifelse Selection Statement Indicate different actions to be perform when condition is true or false Conditional operator (?:)
JavaScripts only ternary operator
Three operands Forms a conditional expression

Dangling-else problem

2004 2003 Prentice Hall, Inc. All rights reserved.

8.6 ifelse Selection Statement

false print Failed

grade >= 60

true print Passed

Fig. 8.4

Flowcharting the double-selection ifelse statement.

2004 2003 Prentice Hall, Inc. All rights reserved.

8.7 while Repetition Statement Repetition structure (loop)


Repeat action while some condition remains true

2004 2003 Prentice Hall, Inc. All rights reserved.

8.7 while Repetition Statement

product <= 1000 false

true

product =

2 * product

Fig. 8.5

Flowcharting the while repetition statement.

2004 2003 Prentice Hall, Inc. All rights reserved.

8.8 Formulating Algorithms: Case Study 1 (Counter-Controlled Repetition) Counter-controlled repetition


Counter
Control the number of times a set of statements executes

Definite repetition

2004 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10

<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Fig. 8.7: average.html --> <!-- Class Average Program <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Class Average Program</title> <script type = "text/javascript"> <!-var total, gradeCounter, gradeValue, average, grade; // sum of grades // number of grades entered // grade value // average of all grades // grade typed by user -->

Outline
average.html (1 of 3)

11 12 13 14 15 16 17 18 19 20 21 22 23 // Initialization Phase total = 0; gradeCounter = 1; // clear total // prepare to loop

2004 2003 Prentice Hall, Inc.


All rights reserved.

24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47

// Processing Phase while ( gradeCounter <= 10 ) { // loop 10 times

Outline
average.html (2 of 3)

// prompt for input and read grade from user grade = window.prompt( "Enter integer grade:", "0" ); // convert grade from a string to an integer gradeValue = parseInt( grade ); // add gradeValue to total total = total + gradeValue; // add 1 to gradeCounter gradeCounter = gradeCounter + 1; } // Termination Phase average = total / 10; // calculate the average

// display average of exam grades document.writeln( "<h1>Class average is " + average + "</h1>" ); // --> </script>

2004 2003 Prentice Hall, Inc.


All rights reserved.

48 49 50 51 52 </head> <body> <p>Click Refresh (or Reload) to run the script again<p> </body>

Outline
average.html (3 of 3)

53 </html>

2004 2003 Prentice Hall, Inc.


All rights reserved.

8.9 Formulating Algorithms with Top-Down, Stepwise Refinement: Case Study 2 (Sentinel-Controlled Repetition) Indefinite repetition
Sentinel value

2004 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11

<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Fig. 8.9: average2.html <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Class Average Program: Sentinel-controlled Repetition</title> <script type = "text/javascript"> <!-var gradeCounter, gradeValue, total, average, grade; // number of grades entered // grade value // sum of grades // average of all grades // grade typed by user --> <!-- Sentinel-controlled Repetition -->

Outline
average2.html (1 of 3)

12 13 14 15 16 17 18 19 20 21 22 23 24 // Initialization phase total = 0; gradeCounter = 0; // clear total // prepare to loop

2004 2003 Prentice Hall, Inc.


All rights reserved.

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47

// Processing phase // prompt for input and read grade from user grade = window.prompt( "Enter Integer Grade, -1 to Quit:", "0" ); // convert grade from a string to an integer gradeValue = parseInt( grade ); while ( gradeValue != -1 ) { // add gradeValue to total total = total + gradeValue; // add 1 to gradeCounter gradeCounter = gradeCounter + 1; // prompt for input and read grade from user grade = window.prompt( "Enter Integer Grade, -1 to Quit:", "0" ); // convert grade from a string to an integer gradeValue = parseInt( grade ); }

Outline
average2.html (2 of 3)

2004 2003 Prentice Hall, Inc.


All rights reserved.

48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64

// Termination phase if ( gradeCounter != 0 ) { average = total / gradeCounter; // display average of exam grades document.writeln( "<h1>Class average is " + average + "</h1>" ); } else document.writeln( "<p>No grades were entered</p>" ); // --> </script> </head> <body> <p>Click Refresh (or Reload) to run the script again</p> </body>

Outline
average2.html (3 of 3)

65 </html>

2004 2003 Prentice Hall, Inc.


All rights reserved.

2004 2003 Prentice Hall, Inc. All rights reserved.

8.10 Formulating Algorithms with Top-Down, Stepwise Refinement: Case Study 3 (Nested Control Structures) Consider problem Make observations Top-down, stepwise refinement

2004 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10

<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Fig. 8.11: analysis.html --> <!-- Analyzing Exam Results <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Analysis of Examination Results</title> <script type = "text/javascript"> <!-// initializing variables in declarations var passes = 0, failures = 0, student = 1, result; // number of passes // number of failures // student counter // one exam result -->

Outline
analysis.html (1 of 2)

11 12 13 14 15 16 17 18 19 20 21 22 23 24 // process 10 students; counter-controlled loop while ( student <= 10 ) { result = window.prompt( "Enter result (1=pass,2=fail)", "0" );

2004 2003 Prentice Hall, Inc.


All rights reserved.

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 </head> <body> }

if ( result == "1" ) passes = passes + 1; else failures = failures + 1; student = student + 1;

Outline
analysis.html (2 of 2)

// termination phase document.writeln( "<h1>Examination Results</h1>" ); document.writeln( "Passed: " + passes + "<br />Failed: " + failures ); if ( passes > 8 ) document.writeln( "<br />Raise Tuition" ); // --> </script>

<p>Click Refresh (or Reload) to run the script again</p> </body>

47 </html>

2004 2003 Prentice Hall, Inc.


All rights reserved.

2004 2003 Prentice Hall, Inc. All rights reserved.

2004 2003 Prentice Hall, Inc. All rights reserved.

8.11 Assignment Operators Compound assignment operators


Abbreviate assignment expressions

2004 2003 Prentice Hall, Inc. All rights reserved.

8.11 Assignment Operators


Assignment Initial operator value of variable += c = 3 Sample Explanation Assigns expression c += 7 + * / % 10 to c 1 to d 20 to e 2 to f 3 to g

c = c 7 -= d = 5 d -= 4 d = d 4 *= e = 4 e *= 5 e = e 5 /= f = 6 f /= 3 f = f 3 %= g = 12 g %= 9 g = g 9 Fig. 8.12 Arithmetic assignment operators.

2004 2003 Prentice Hall, Inc. All rights reserved.

8.12 Increment and Decrement Operators Preincrement or predecrement operator


Increment of decrement operator placed before a variable

Postincrement or postdecrement operator


Increment of decrement operator placed after a variable

2004 2003 Prentice Hall, Inc. All rights reserved.

8.12 Increment and Decrement Operators


Operator Called ++ Sample expression preincrement ++a Explanation

Increment a by 1, then use the new value of a in the expression in which a resides. postincrement a++ Use the current value of a in ++ the expression in which a resides, then increment a by 1. predecrement --b Decrement b by 1, then use the -new value of b in the expression in which b resides. postdecrement b-Use the current value of b in -the expression in which b resides, then decrement b by 1. Fig. 8.13 increment and decrement operators.

2004 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10

<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Fig. 8.14: increment.html <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Preincrementing and Postincrementing</title> <script type = "text/javascript"> <!-var c; c = 5; document.writeln( "<h3>Postincrementing</h3>" ); document.writeln( c ); // print 5 then increment document.writeln( "<br />" + c++ ); document.writeln( "<br />" + c ); c = 5; document.writeln( "<h3>Preincrementing</h3>" ); document.writeln( c ); // print 5 // print 6 // print 5 --> <!-- Preincrementing and Postincrementing -->

Outline
increment.html (1 of 2)

11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

2004 2003 Prentice Hall, Inc.


All rights reserved.

26 27 28 29 30 31 32

// increment then print 6 document.writeln( "<br />" + ++c ); document.writeln( "<br />" + c ); // --> </script> </head><body></body> // print 6

Outline
increment.html (2 of 2)

33 </html>

2004 2003 Prentice Hall, Inc.


All rights reserved.

8.12 Increment and Decrement Operators


Operator Associativity Type right to left unary ++ -left to right multiplicative * / % left to right additive + left to right relational < <= > >= left to right equality == != right to left conditional ?: assignment = += -= *= /= %= right to left Fig. 8.15 Precedence and associativity of the operators discussed so far.

2004 2003 Prentice Hall, Inc. All rights reserved.

8.13 Note on Data Types Loosely typed


Automatically converts between values of different types

2004 2003 Prentice Hall, Inc. All rights reserved.

8.14 Web Resources


www.javascriptmall.com developer.netscape.com/tech/javascript www.mozilla.org/js/language

2004 2003 Prentice Hall, Inc. All rights reserved.

You might also like