Download presentation
Presentation is loading. Please wait.
Published byDwain Harmon Modified over 9 years ago
1
2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 8 - JavaScript: Control Structures I Outline 8.1 Introduction 8.2 Algorithms 8.3 Pseudocode 8.4 Control Structures 8.5 if Selection Structure 8.6 if/else Selection Structure 8.7 while Repetition Structure 8.8 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 JavaScript Internet and World Wide Web Resources
2
2001 Prentice Hall, Inc. All rights reserved. 2 All programs can be written in terms of three control structures 1. Sequence structure 2. Selection structure 3. Repetition structure Control Structures
3
2001 Prentice Hall, Inc. All rights reserved. 3 8.4 Control Structure - Sequence Fig. 8.1Flowcharting JavaScript’s sequence structure.
4
2001 Prentice Hall, Inc. All rights reserved. 4 8.4 JavaScript Key Words
5
2001 Prentice Hall, Inc. All rights reserved. 5 Pseudocode: If student’s grade is greater than or equal to 60 Print “Passed” JavaScript statement: if( grade >= 60 ) document.writeln( “Passed” ); –Proper syntax: indent all lines within structure Flowchart: if Selection Structure print “Passed” False True grade >= 60
6
2001 Prentice Hall, Inc. All rights reserved. 6 Conditions which evaluate to true –True condition –Non-zero numeric value –String containing at least one character Conditions which evaluate to false –False condition –Numeric value = 0 –Empty string –Variable with no assigned value if Selection Structure
7
2001 Prentice Hall, Inc. All rights reserved. 7 8.6 if Selection Structure Fig. 8.3Flowcharting the single-selection if structure.
8
2001 Prentice Hall, Inc. All rights reserved. 8 Pseudocode: If student’s grade is greater than or equal to 60 Print “Passed” else Print “Failed” JavaScript statement: if ( grade >= 60 ) document.writeln( “Passed” ); else document.writeln( “Failed” ); if/else Selection Structure
9
2001 Prentice Hall, Inc. All rights reserved. 9 Flowchart if/else Selection Structure print “Passed” grade >= 60 print “Failed” FalseTrue
10
2001 Prentice Hall, Inc. All rights reserved. 10 Conditional Operator ( ?: ) –JavaScript’s only ternary operator –Takes three operands 1. Boolean expression 2. Value for conditional expression if true 3. Value for conditional expression if false –Example document.writeln( studentGrade >= 60 ? “Passed” : “Failed” ); Same operation as preceding if/else statement if/else Selection Structure
11
2001 Prentice Hall, Inc. All rights reserved. 11 Pseudocode: If student’s grade is greater than or equal to 90 Print “A” else If Student’s grade is greater than or equal to 80 Print “B” else If student’s grade is greater than or equal to 70 Print “C” else If student’s grade is greater than or equal to 60 Print “D” else Print “F” Nested if/else Selection Structure
12
2001 Prentice Hall, Inc. All rights reserved. 12 JavaScript statement: if ( studentGrade >= 90 ) document.writeln( “A” ); else if ( studentGrade >= 80 ) document.writeln( “B” ); else if ( studentGrade >= 70 ) document.writeln( “C” ); else if ( studentGrade >= 60 ) document.writeln( “D” ); else document.writeln( “F” ); Nested if/else Selection Structure
13
2001 Prentice Hall, Inc. All rights reserved. 13 Identical JavaScript statement: if ( studentGrade >= 90 ) document.writeln( “A” ); else if ( studentGrade >= 80 ) document.writeln( “B” ); else if ( studentGrade >= 70 ) document.writeln( “C” ); else if ( studentGrade >= 60 ) document.writeln( “D” ); else document.writeln( “F” ); –This form preferred by many because avoids deep indent Nested if/else Selection Structure
14
2001 Prentice Hall, Inc. All rights reserved. 14 JavaScript interpreter Associates else statement with previous if statement unless indicated otherwise by braces ( {} ) –Example: if ( x > 5 ) if ( y > 5 ) document.writeln( “x and y are > 5” ); else document.writeln( “x is <= 5” ); Dangling-else Problem
15
2001 Prentice Hall, Inc. All rights reserved. 15 Because of indent, appears that else statement applies to first if statement –JavaScript interpreter really reads as: if ( x > 5 ) if ( y > 5 ) document.writeln( “x and y are > 5” ); else document.writeln( “x is <= 5” ); Dangling-else Problem
16
2001 Prentice Hall, Inc. All rights reserved. 16 To have JavaScript interpreter read structure as you intended, utilize braces ( {} ) if ( x > 5 ) { if ( y > 5 ) document.writeln( “x and y are > 5” ); } else document.writeln( “x is <= 5” ); else statement now applies to first if statement Use braces to solve Dangling-else Problem
17
2001 Prentice Hall, Inc. All rights reserved. 17 Compound Statement: –Statement contained inside braces ( { and } ) –Does not end with a semi-colon All statements inside should end with semi-colons Example: if ( grade >= 60 ) document.writeln( “Passed” ); else { document.writeln( “Failed ” ); document.writeln( “You must take the course again.” ); } –JavaScript interpreter executes both writeln statements inside braces if the if condition is false –Without braces, last writeln statement outside if/else structure and will always execute Compound Statement
18
2001 Prentice Hall, Inc. All rights reserved. 18 8.6 if/else Selection Structure grade >= 60 true print “ Failed ” false print “ Passed ” Fig. 8.4Flowcharting the double-selection if/else structure.
19
2001 Prentice Hall, Inc. All rights reserved. 19 Program segment: find first power of 2 larger than 1000 Pseudocode : While product is less than 1000 multiply product by 2 JavaScript statement: var product = 2; while ( product <= 1000 ) product = 2 * product; Flowchart: product = 2 * product False True product <= 1000 while Repetition Structure
20
2001 Prentice Hall, Inc. All rights reserved. 20 –Uses a while repetition structure Tests if variable counter has reached the target value using relative condition counter incremented or decremented a set amount every loop Structure concludes when condition becomes false (i.e.: counter reaches target value) –Used With or without user input When there is a known number of loops Counter-Controlled Repetition
21
2001 Prentice Hall, Inc. All rights reserved. 21 Counter-Controlled Repetition product <=1000 true false Fig. 8.5Flowcharting the while repetition structure.
22
2001 Prentice Hall, Inc. All rights reserved. Outline 22 Average.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 6 7 8 9 10 Class Average Program 11 12 13 <!-- 14 var total, // sum of grades 15 gradeCounter, // number of grades entered 16 gradeValue, // grade value 17 average, // average of all grades 18 grade; // grade typed by user 19 20 // Initialization Phase 21 total = 0; // clear total 22 gradeCounter = 1; // prepare to loop 23 24 // Processing Phase 25 while ( gradeCounter <= 10 ) { // loop 10 times 26 27 // prompt for input and read grade from user 28 grade = window.prompt( "Enter integer grade:", "0" ); 29 30 // convert grade from a string to an integer 31 gradeValue = parseInt( grade ); 32 33 // add gradeValue to total 34 total = total + gradeValue; 35 The while loop will execute the statements in the body of the loop until the value of gradeCounter equals 10. Prompt for the user input a grade.Convert input to an integer. Add new grade to total.
23
2001 Prentice Hall, Inc. All rights reserved. Outline 23 Average.html Program Output 36 // add 1 to gradeCounter 37 gradeCounter = gradeCounter + 1; 38 } 39 40 // Termination Phase 41 average = total / 10; // calculate the average 42 43 // display average of exam grades 44 document.writeln( 45 " Class average is " + average + " " ); 46 // --> 47 48 49 50 51 Click Refresh (or Reload) to run the script again 52 53 Increment the counter. Calculate the average of the grades input by the user. Write the result to the XHTML document.
24
2001 Prentice Hall, Inc. All rights reserved. 24 –Uses a while repetition structure Tests if variable counter has been set to sentinel value using equality condition When user inputs string equal to sentinel value, condition will be false next time tested –Used when User input is incorporated into structure Final number of loops unknown – indefinite repetition –First user input should occur before while structure begins Be sure to account for possibility of user initially entering sentinel value - also called priming –Sentinel value chosen so not confused with an acceptable input value -1 is a common sentinel value Sentinel-Controlled Repetition:
25
2001 Prentice Hall, Inc. All rights reserved. Outline 25 Average2.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 6 7 8 9 10 Class Average Program: 11 Sentinel-controlled Repetition 12 13 14 <!-- 15 var gradeCounter, // number of grades entered 16 gradeValue, // grade value 17 total, // sum of grades 18 average, // average of all grades 19 grade; // grade typed by user 20 21 // Initialization phase 22 total = 0; // clear total 23 gradeCounter = 0; // prepare to loop 24 25 // Processing phase 26 // prompt for input and read grade from user 27 grade = window.prompt( 28 "Enter Integer Grade, -1 to Quit:", "0" ); 29 30 // convert grade from a string to an integer 31 gradeValue = parseInt( grade ); 32 33 while ( gradeValue != -1 ) { 34 // add gradeValue to total 35 total = total + gradeValue; Prompt for the user to enter a grade, -1 to end.The while loop will continue until the user input equals –1.
26
2001 Prentice Hall, Inc. All rights reserved. Outline 26 Average2.html 36 37 // add 1 to gradeCounter 38 gradeCounter = gradeCounter + 1; 39 40 // prompt for input and read grade from user 41 grade = window.prompt( 42 "Enter Integer Grade, -1 to Quit:", "0" ); 43 44 // convert grade from a string to an integer 45 gradeValue = parseInt( grade ); 46 } 47 48 // Termination phase 49 if ( gradeCounter != 0 ) { 50 average = total / gradeCounter; 51 52 // display average of exam grades 53 document.writeln( 54 " Class average is " + average + " " ); 55 } 56 else 57 document.writeln( " No grades were entered " ); 58 // --> 59 60 61 62 63 Click Refresh (or Reload) to run the script again 64 65 Each iteration of the loop will open a prompt dialog allowing the user to input another grade.
27
2001 Prentice Hall, Inc. All rights reserved. Outline 27 Program Output
28
2001 Prentice Hall, Inc. All rights reserved. 28 Nested Control Structures –Control structures may be placed inside other control structures –May be done as many times as necessary –Can accomplish goals of program faster and with fewer complications –Be sure to Map out your algorithm with pseudocode and/or flowchart before programming Insert comments into program to aid debugging Variable initialization –Values may be assigned to variables in initialization statement –If variable not introduced, will be automatically initialized by JavaScript Control Structures in while loop
29
2001 Prentice Hall, Inc. All rights reserved. Outline 29 Analysis.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 6 7 8 9 10 Analysis of Examination Results 11 12 13 <!-- 14 // initializing variables in declarations 15 var passes = 0, // number of passes 16 failures = 0, // number of failures 17 student = 1, // student counter 18 result; // one exam result 19 20 // process 10 students; counter-controlled loop 21 while ( student <= 10 ) { 22 result = window.prompt( 23 "Enter result (1=pass,2=fail)", "0" ); 24 25 if ( result == "1" ) 26 passes = passes + 1; 27 else 28 failures = failures + 1; 29 30 student = student + 1; 31 } 32 The while loop will continue until the value of student is 10 meaning 10 results were entered. Entering a 1 into the prompt dialog means the student passed the exam. A value of 2 means the student failed. If a value of 1 was entered, the value of passes is incremented by one, otherwise, failures is incremented.
30
2001 Prentice Hall, Inc. All rights reserved. Outline 30 Analysis.html 33 // termination phase 34 document.writeln( " Examination Results " ); 35 document.writeln( 36 "Passed: " + passes + " Failed: " + failures ); 37 38 if ( passes > 8 ) 39 document.writeln( " Raise Tuition" ); 40 // --> 41 42 43 44 45 Click Refresh (or Reload) to run the script again 46 47 If more than 8 students passed the exam, the program says to “Raise Tuition”.
31
2001 Prentice Hall, Inc. All rights reserved. Outline 31 Program Output
32
2001 Prentice Hall, Inc. All rights reserved. 32 Assignment operations with identical results can be written different ways –Example 1: c = c + 3; –Example 2: c += 3; Both ways add 3 to the value of c Example 2 executes faster –Small difference for individual operations –Significant over large number of operations Assignment Operators
33
2001 Prentice Hall, Inc. All rights reserved. 33 Compound Assignment Operators Arithmetic Assignment Operators
34
2001 Prentice Hall, Inc. All rights reserved. 34 Increment operator ( ++ ) –Example: c++; is identical to c += 1; is identical to c = c + 1; Decrement operator ( -- ) –Example: c--; is identical to c -= 1; is identical to c = c - 1; Faster operation – –Save time over many repetitions Can be preincremented/decremented or postincremented/decremented –Only makes a difference when variable appears in context of larger expression Increment and Decrement Operators
35
2001 Prentice Hall, Inc. All rights reserved. 35 Increment and Decrement Operators
36
2001 Prentice Hall, Inc. All rights reserved. 36 8.12 Increment and Decrement Operators
37
2001 Prentice Hall, Inc. All rights reserved. Outline 37 Increment.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 6 7 8 9 10 Preincrementing and Postincrementing 11 12 13 <!-- 14 var c; 15 16 c = 5; 17 document.writeln( " Postincrementing " ); 18 document.writeln( c ); // print 5 19 // print 5 then increment 20 document.writeln( " " + c++ ); 21 document.writeln( " " + c ); // print 6 22 23 c = 5; 24 document.writeln( " Preincrementing " ); 25 document.writeln( c ); // print 5 26 // increment then print 6 27 document.writeln( " " + ++c ); 28 document.writeln( " " + c ); // print 6 29 // --> 30 31 32 33 Postincrementing the variable will print the variable and then increment the value by one. Preincrementing the variable will increment the value by one and then print the value.
38
2001 Prentice Hall, Inc. All rights reserved. Outline 38 Program Output
39
2001 Prentice Hall, Inc. All rights reserved. 39 Assignment statements passes = passes + 1; Assignment operators passes += 1; Preincrement operators ++passes; Postincrement operators passes++; The following return identical results:
40
2001 Prentice Hall, Inc. All rights reserved. 40 JavaScript - loosely typed language –Does not require variable to have type before use in program (unlike other languages) –Variable can contain a value of any data type –JavaScript often converts between values of different types automatically When declaring variables –If not given value, variable has undefined value –To indicate variable has no value, assign it null A Note on Data Types
41
2001 Prentice Hall, Inc. All rights reserved. 41 8.13 Note on Data Types
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.