Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
1 Chapter 4 - Control Structures: Part 1 Outline 4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8 4.9 4.10 4.11 4.12 4.13 4.14 Introduction Algorithms Pseudocode Control Structures The if Selection Structure The if/else Selection Structure The while Repetition Structure Formulating Algorithms: Case Study 1 (CounterControlled Repetition) Formulating Algorithms with Top-Down, Stepwise Refinement: Case Study 2 (Sentinel-Controlled Repetition) Formulating Algorithms with Top-Down, Stepwise Refinement: Case Study 3 (Nested Control Structures) Assignment Operators Increment and Decrement Operators Primitive Data Types (Optional Case Study) Thinking About Objects: Identifying Class Attributes Introduction, Algorithms, Pseudocode, Control Structure 2 • We learn about Control Structures – Structured-programming principle – Control structures help build and manipulate objects (Chapter 8) • Algorithm: Series of actions in specific order • Program control(structures) : Specify the order in which actions execute • Pseudocode – Informal language for developing algorithms – Not executed on computers – Helps developers “think out” algorithms • Sequential execution:Program statements execute one after the other • Transfer of control: Three control statements specify order of statements • Sequence structure • Selection structure • Repetition structure • Flowchart: Graphical representation of algorithm 3 Flowlines Action Symbols add grade to total total = total + grade; add 1 to counter counter = counter + 1; Connector Symbols Fig 4.1 Flowcharting Java’s sequence structure. 4 Java Keywords abstract boolean break byte case catch do final implements long private static char double finally import native protected super class else float instanceof new public switch continue extends for int null return synchronized default false if interface package short this transient while true try throw throws void volatile Keywords that are reserved, but not used, by Java const goto Fig. 4.2 Java keywords. Selection Structures • Java has a sequence structure “built-in” • Java provides three selection structures – If; if/else; switch • Java provides three repetition structures – While; do/while; do • If – Single-entry/single-exit structure – Perform action only when condition is true – Action/decision programming model • if/else – – – – Perform action only when condition is true Perform different specified action when condition is false Conditional operator (?:) Nested if/else selection structures • While – Repeat action while condition remains true 5 6 Decision Symbol grade >= 60 true print “Passed” false Fig 4.3 Flowcharting the single-selection if structure. 7 false true grade >= 60 print “Failed” print “Passed” Fig 4.4 Flowcharting the double-selection if/else structure. 8 true product <= 1000 product = 2 * product false Fig 4.5 Flowcharting the while repetition structure. Formulating Algorithms: Case Study 1 (Counter-Controlled Repetition) • Counter – Variable that controls number of times set of statements executes • Average1.java calculates grade averages – uses counters to control repetition Set total to zero Set grade counter to one While grade counter is less than or equal to ten Input the next grade Add the grade into the total Add one to the grade counter Set the class average to the total divided by ten Print the class average Fig. 4.6 Pseudocode algorithm that uses countercontrolled repetition to solve the class-average problem. 9 10 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 Outline // Fig. 4.7: Average1.java // Class average program with counter-controlled repetition. // Java extension packages import javax.swing.JOptionPane; Declare variables; gradeCounter is the counter public class Average1 { Average1.java gradeCounter // main method begins execution of Java application public static void main( String args[] ) { int total, // sum of grades input by user gradeCounter, // number of grades entered Continue looping as long as gradeValue, // grade value is less than or average; // average ofgradeCounter all grades String grade; // grade typed by userequal to 10 Line 23 // Initialization Phase total = 0; // clear total gradeCounter = 1; // prepare to loop // Processing Phase while ( gradeCounter <= 10 ) { // loop 10 times // prompt for input and read grade from user grade = JOptionPane.showInputDialog( "Enter integer grade: " ); // convert grade from a String to an integer gradeValue = Integer.parseInt( grade ); // add gradeValue to total total = total + gradeValue; 2002 Prentice Hall. All rights reserved. 11 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 } // add 1 to gradeCounter gradeCounter = gradeCounter + 1; } // end while structure // Termination Phase average = total / 10; Outline Average1.java // perform integer division // display average of exam grades JOptionPane.showMessageDialog( null, "Class average is " + average, "Class Average", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); } // terminate the program // end method main // end class Average1 2002 Prentice Hall. All rights reserved. 12 Outline Average1.java 2002 Prentice Hall. All rights reserved. Formulating Algorithms with Top-Down, Stepwise Refinement: Case Study 2 (Sentinel-Controlled Repetition) • Sentinel value: Used to indicated the end of data entry • Average2.java has indefinite repetition – User enters sentinel value (-1) to end repetition Initialize total to zero Initialize counter to zero Input the first grade (possibly the sentinel) While the user has not as yet entered the sentinel Add this grade into the running total Add one to the grade counter Input the next grade (possibly the sentinel) If the counter is not equal to zero Set the average to the total divided by the counter Print the average else Print “No grades were entered” Fig. 4.8 Pseudocode algorithm that uses sentinel-controlled repetition to solve the class-average problem. 13 14 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 // Fig. 4.9: Average2.java // Class average program with sentinel-controlled repetition. // Java core packages import java.text.DecimalFormat; Outline Average2.java // Java extension packages import javax.swing.JOptionPane; public class Average2 { // main method begins execution of Java application public static void main( String args[] ) { int gradeCounter, // number of grades entered gradeValue, // grade value total; // sum of grades double average; // average of all grades String input; // grade typed by user // Initialization phase total = 0; // clear total gradeCounter = 0; // prepare to loop // Processing phase // prompt for input and read grade from user input = JOptionPane.showInputDialog( "Enter Integer Grade, -1 to Quit:" ); // convert grade from a String to an integer gradeValue = Integer.parseInt( input ); 2002 Prentice Hall. All rights reserved. 15 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 Outline while ( gradeValue != -1 ) { // add gradeValue to total total = total + gradeValue; loop until gradeCounter equals sentinel value (-1) // add 1 to gradeCounter gradeCounter = gradeCounter + 1; Line 33 // prompt for input and read grade from user input = JOptionPane.showInputDialog( "Enter Integer Grade, -1 to Quit:" ); } Average2.java Line 50 // convert grade from a String to an integer gradeValue = Integer.parseInt( input ); Format numbers to nearest hundredth // Termination phase DecimalFormat twoDigits = new DecimalFormat( "0.00" ); if ( gradeCounter != 0 ) { average = (double) total / gradeCounter; // display average of exam grades JOptionPane.showMessageDialog( null, "Class average is " + twoDigits.format( average ), "Class Average", JOptionPane.INFORMATION_MESSAGE ); } else JOptionPane.showMessageDialog( null, "No grades were entered", "Class Average", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); // terminate application 2002 Prentice Hall. All rights reserved. 16 67 68 69 } } // end method main Outline // end class Average2 Average2.java 2002 Prentice Hall. All rights reserved. Formulating Algorithms with Top-Down, Stepwise Refinement: Case Study 3(Nested Control Structures) • Nested control structures Initialize passes to zero Initialize failures to zero Initialize student to one While student counter is less than or equal to ten Input the next exam result If the student passed Add one to passes else Add one to failures Add one to student counter Print the number of passes Print the number of failures If more than eight students passed Print “Raise tuition” Fig 4.10 Pseudocode for examination-results problem. 17 18 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 Outline // Fig. 4.11: Analysis.java // Analysis of examination results. // Java extension packages import javax.swing.JOptionPane; public class Analysis { Loop until student counter is greater than 10 // main method begins execution of Java application public static void main( String args[] ) { // initializing variables in declarations int passes = 0, // number of passes failures = 0, // number of failures student = 1, // student counter result; // one exam result String input, // user-entered value output; // output string // process 10 students; counter-controlled loop while ( student <= 10 ) { Nested control Analysis.java Line 21 Line 31 structure // obtain result from user input = JOptionPane.showInputDialog( "Enter result (1=pass,2=fail)" ); // convert result to int result = Integer.parseInt( input ); // process result if ( result == 1 ) passes = passes + 1; else failures = failures + 1; 2002 Prentice Hall. All rights reserved. 19 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 } student = student + 1; Outline } // termination phase output = "Passed: " + passes + "\nFailed: " + failures; Analysis.java if ( passes > 8 ) output = output + "\nRaise Tuition"; JOptionPane.showMessageDialog( null, output, "Analysis of Examination Results", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); } // terminate application // end method main // end class Analysis 2002 Prentice Hall. All rights reserved. 20 Assignment Operators • Assignment Operators – Abbreviate assignment expressions • variable = variable operator expression; //Can be written as • variable operator= expression; – e.g., addition assignment operator += • c = c + 3; // can be written as • c += 3 Assignment operator Assume: int c = 3, d = 5, e = 4, f = 6, g = 12; += -= *= /= %= Sample expression Explanation Assigns c d e f g c d e f g 10 to c 1 to d 20 to e 2 to f 3 to g += -= *= /= %= 7 4 5 3 9 = = = = = c d e f g + * / % 7 4 5 3 9 Fig. 4.12 Arithmetic assignment operators. Increment and Decrement Operators • Unary increment (++) and decrement (--) operators • Preincrement / predecrement operator • Post-increment / post-decrement operator Operator ++ Called preincrement Sample expression ++a ++ postincrement a++ -- predecrement --b -- postdecrement b-- Explanation Increment a by 1, then use the new value of a in the expression in which a resides. Use the current value of a in the expression in which a resides, then increment a by 1. Decrement b by 1, then use the new value of b in the expression in which b resides. Use the current value of b in the expression in which b resides, then decrement b by 1. Fig. 4.13 The increment and decrement operators. 21 22 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Outline // Fig. 4.14: Increment.java // Preincrementing and postincrementing public class Increment { Line 13 postincrements c // main method begins execution of Java application public static void main( String args[] ) { int c; Line 20 preincrements c = 5; System.out.println( c ); // print 5 System.out.println( c++ ); // print 5 then postincrement System.out.println( c ); // print 6 System.out.println(); Increment.java Line 13 postincrement c Line 20 preincrement // skip a line c = 5; System.out.println( c ); // print 5 System.out.println( ++c ); // preincrement then print 6 System.out.println( c ); // print 6 } } // end method main // end class Increment 5 5 6 5 6 6 2002 Prentice Hall. All rights reserved. 23 Operators () Associativity left to right Type parentheses ++ -- right to left unary postfix right to left unary left to right multiplicative left to right additive left to right relational == != left to right equality ?: right to left conditional right to left assignment ++ -- + * / + - < <= > = - (type) % >= += -= *= /= %= Fig. 4.15 Precedence and associativity of the operators discussed so far. Primitive Data Types 24 – Primitive types: “building blocks” for more complicated types – Java is strongly typed: All variables in a Java program must have a type – primitive types: portable across computer platforms that support Java Type boolean Size in bits 8 Values true or false Standard char 16 (ISO Unicode character set) byte 8 short 16 int 32 long 64 float 32 double 64 ’\u0000’ to ’\uFFFF’ (0 to 65535) –128 to +127 (–27 to 27 – 1) –32,768 to +32,767 (–215 to 215 – 1) –2,147,483,648 to +2,147,483,647 (–231 to 231 – 1) –9,223,372,036,854,775,808 to +9,223,372,036,854,775,807 (–263 to 263 – 1) Negative range: –3.4028234663852886E+38 to –1.40129846432481707e–45 Positive range: 1.40129846432481707e–45 to 3.4028234663852886E+38 Negative range: –1.7976931348623157E+308 to –4.94065645841246544e–324 Positive range: 4.94065645841246544e–324 to 1.7976931348623157E+308 Fig. 4.16 The Java primitive data types. (IEEE 754 floating point) (IEEE 754 floating point) (Optional Case Study) Thinking About Objects: Identifying Class Attributes • Classes have attributes (data) – Implemented in Java programs as variables – Attributes of real-world objects • Radio (object) – Station setting, volume setting, AM or FM (attributes) • Identify attributes – Look for descriptive words and phrases in problem statement – Each identified word and phrase is a candidate attribute • e.g., “the elevator is moving” – “is moving” corresponds to boolean attribute moving • e.g., “the elevator takes five seconds to travel between floors” – corresponds to int attribute travelTime • int travelTime = 5; (in Java) 25 26 Class ElevatorModel Descriptive words and phrases number of people in the simulation ElevatorShaft Elevator [no descriptive words or phrases] moving summoned current floor destination floor capacity of only one person five seconds to travel between floors unique waiting / moving current floor first or second; capacity for only one person pressed / reset pressed / reset door closed / door open door closed / door open [no descriptive words or phrases] illuminated / turned off Person Floor FloorButton ElevatorButton FloorDoor ElevatorDoor Bell Light Fig. 4.17 Descriptive words and phrases from problem statement. Identifying Class Attributes (cont.) • UML class diagram: attributes are place in the middle compartment 27 – Attributes are written language independently: • attribute open of class ElevatorDoor: open : Boolean = false • May be coded in Java as: boolean open = false; Eleva to rMo del numb erOfPe ople : Integ er=0 Elev atorShaft <none ye t> Perso n ID : Integer mov ing : Boolea n = true c urrentFloor : Intege r Elev ator mo ving : Boo le an = false summ oned : Boolea n = fa lse c urrentFloo r : Integ er = 1 de stinationFlo or : Integer = 2 c a pa c ity : Inte ger = 1 tra velTime : Integer = 5 Eleva to rDoor ope n : Boolean = fa lse Floo r floorNumbe r : Integ er c ap ac ity : Integ er = 1 Light lightOn : Boolea n = fa lse Bell Eleva to rButton pressed : Boolea n = fa lse FloorButto n pressed : Boolea n = fa lse Fig. 4.18 Classes with attributes. <no ne yet> FloorDo or ope n : Boolean = fa lse