1 Chapter 4 Control Structures Part 1 Outline

  • Slides: 40
Download presentation
1 Chapter 4 - Control Structures: Part 1 Outline 4. 1 4. 2 4.

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 (Counter. Controlled 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 2002 Prentice Hall. All rights reserved.

2 4. 1 Introduction • We learn about Control Structures – Structured-programming principle –

2 4. 1 Introduction • We learn about Control Structures – Structured-programming principle – Control structures help build and manipulate objects (Chapter 8) 2002 Prentice Hall. All rights reserved.

3 4. 2 Algorithms • Algorithm – Series of actions in specific order •

3 4. 2 Algorithms • Algorithm – Series of actions in specific order • The actions executed • The order in which actions execute • Program control – Specifying the order in which actions execute • Control structures help specify this order 2002 Prentice Hall. All rights reserved.

4 4. 3 Pseudocode • Pseudocode – Informal language for developing algorithms – Not

4 4. 3 Pseudocode • Pseudocode – Informal language for developing algorithms – Not executed on computers – Helps developers “think out” algorithms 2002 Prentice Hall. All rights reserved.

5 4. 4 Control Structures • Sequential execution – Program statements execute one after

5 4. 4 Control Structures • Sequential execution – Program statements execute one after the other • Transfer of control – Three control statements can specify order of statements • Sequence structure • Selection structure • Repetition structure • Flowchart – Graphical representation of algorithm • Flowlines indicate order in which actions execute 2002 Prentice Hall. All rights reserved.

6 Flowlines Action Symbols add grade to total = total + grade; add 1

6 Flowlines Action Symbols add grade to total = total + grade; add 1 to counter = counter + 1; Connector Symbols Fig 4. 1 Flowcharting Java’s sequence structure. 2002 Prentice Hall. All rights reserved.

7 2002 Prentice Hall. All rights reserved.

7 2002 Prentice Hall. All rights reserved.

8 Selection Structures • Java has a sequence structure “built-in” • Java provides three

8 Selection Structures • Java has a sequence structure “built-in” • Java provides three selection structures – if/else – switch • Java provides three repetition structures – while – do/while – do • Each of these words is a Java keyword 2002 Prentice Hall. All rights reserved.

9 4. 5 The if Selection Structure • Single-entry/single-exit structure • Perform action only

9 4. 5 The if Selection Structure • Single-entry/single-exit structure • Perform action only when condition is true • Action/decision programming model 2002 Prentice Hall. All rights reserved.

10 Decision Symbol grade >= 60 true print “Passed” false Fig 4. 3 Flowcharting

10 Decision Symbol grade >= 60 true print “Passed” false Fig 4. 3 Flowcharting the single-selection if structure. 2002 Prentice Hall. All rights reserved.

11 4. 6 The if/else Selection Structure • Perform action only when condition is

11 4. 6 The if/else Selection Structure • Perform action only when condition is true • Perform different specified action when condition is false • Conditional operator (? : ) • Nested if/else selection structures 2002 Prentice Hall. All rights reserved.

12 false true grade >= 60 print “Failed” print “Passed” Fig 4. 4 Flowcharting

12 false true grade >= 60 print “Failed” print “Passed” Fig 4. 4 Flowcharting the double-selection if/else structure. 2002 Prentice Hall. All rights reserved.

13 4. 7 The while Repetition Structure • Repeat action while condition remains true

13 4. 7 The while Repetition Structure • Repeat action while condition remains true 2002 Prentice Hall. All rights reserved.

14 true product <= 1000 product = 2 * product false Fig 4. 5

14 true product <= 1000 product = 2 * product false Fig 4. 5 Flowcharting the while repetition structure. 2002 Prentice Hall. All rights reserved.

4. 8 Formulating Algorithms: Case Study 1 (Counter-Controlled Repetition) • Counter – Variable that

4. 8 Formulating Algorithms: Case Study 1 (Counter-Controlled Repetition) • Counter – Variable that controls number of times set of statements executes • Average 1. java calculates grade averages – uses counters to control repetition 2002 Prentice Hall. All rights reserved. 15

16 Set total to zero Set grade counter to one While grade counter is

16 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. 2002 Prentice Hall. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 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 33 34 Outline // Fig. 4. 7: Average 1. java // Class average program with counter-controlled repetition. // Java extension packages import javax. swing. JOption. Pane; Declare variables; grade. Counter is the counter public class Average 1 { // main method begins execution of Java application public static void main( String args[] ) { int total, // sum of grades input by user grade. Counter, // number of grades entered Continue looping as long as grade. Value, // grade value is less than or average; // average ofgrade. Counter all grades String grade; // grade typed by userequal to 10 // Initialization Phase total = 0; // clear total grade. Counter = 1; // prepare to loop // Processing Phase while ( grade. Counter <= 10 ) { Average 1. java grade. Counter Line 23 // loop 10 times // prompt for input and read grade from user grade = JOption. Pane. show. Input. Dialog( "Enter integer grade: " ); // convert grade from a String to an integer grade. Value = Integer. parse. Int( grade ); // add grade. Value to total = total + grade. Value; 2002 Prentice Hall. All rights reserved. 17

35 36 37 38 39 40 41 42 43 44 45 46 47 48

35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 } // add 1 to grade. Counter = grade. Counter + 1; } Outline // end while structure // Termination Phase average = total / 10; // perform integer division // display average of exam grades JOption. Pane. show. Message. Dialog( null, "Class average is " + average, "Class Average", JOption. Pane. INFORMATION_MESSAGE ); System. exit( 0 ); } // terminate the program // end method main // end class Average 1. java 2002 Prentice Hall. All rights reserved. 18

Outline Average 1. java 2002 Prentice Hall. All rights reserved. 19

Outline Average 1. java 2002 Prentice Hall. All rights reserved. 19

4. 9 Formulating Algorithms with Top. Down, Stepwise Refinement: Case Study 2 (Sentinel-Controlled Repetition)

4. 9 Formulating Algorithms with Top. Down, Stepwise Refinement: Case Study 2 (Sentinel-Controlled Repetition) • Sentinel value – Used to indicated the end of data entry • Average 2. java has indefinite repetition – User enters sentinel value (-1) to end repetition 2002 Prentice Hall. All rights reserved. 20

21 Initialize total to zero Initialize counter to zero Input the first grade (possibly

21 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. 2002 Prentice Hall. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 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: Average 2. java // Class average program with sentinel-controlled repetition. Outline // Java core packages import java. text. Decimal. Format; // Java extension packages import javax. swing. JOption. Pane; public class Average 2 { // main method begins execution of Java application public static void main( String args[] ) { int grade. Counter, // number of grades entered grade. Value, // grade value total; // sum of grades double average; // average of all grades String input; // grade typed by user Average 2. java // Initialization phase total = 0; // clear total grade. Counter = 0; // prepare to loop // Processing phase // prompt for input and read grade from user input = JOption. Pane. show. Input. Dialog( "Enter Integer Grade, -1 to Quit: " ); // convert grade from a String to an integer grade. Value = Integer. parse. Int( input ); 2002 Prentice Hall. All rights reserved. 22

33 34 35 36 37 38 39 40 41 42 43 44 45 46

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 ( grade. Value != -1 ) { // add grade. Value to total = total + grade. Value; loop until grade. Counter equals sentinel value (-1) // add 1 to grade. Counter = grade. Counter + 1; // prompt for input and read grade from user input = JOption. Pane. show. Input. Dialog( "Enter Integer Grade, -1 to Quit: " Format); numbers to nearest hundredth integer // convert grade from a String to an grade. Value = Integer. parse. Int( input ); } // Termination phase Decimal. Format two. Digits = new Decimal. Format( "0. 00" ); if ( grade. Counter != 0 ) { average = (double) total / grade. Counter; Average 2. java Line 33 Line 50 // display average of exam grades JOption. Pane. show. Message. Dialog( null, "Class average is " + two. Digits. format( average ), "Class Average" , JOption. Pane. INFORMATION_MESSAGE ); } else JOption. Pane. show. Message. Dialog( null, "No grades were entered" , "Class Average", JOption. Pane. INFORMATION_MESSAGE ); System. exit( 0 ); // terminate application 2002 Prentice Hall. All rights reserved. 23

67 68 69 } } // end method main Outline // end class Average

67 68 69 } } // end method main Outline // end class Average 2. java 2002 Prentice Hall. All rights reserved. 24

4. 10 Formulating Algorithms with Top. Down, Stepwise Refinement: Case Study 3 (Nested Control

4. 10 Formulating Algorithms with Top. Down, Stepwise Refinement: Case Study 3 (Nested Control Structures) • Nested control structures 2002 Prentice Hall. All rights reserved. 25

26 Initialize passes to zero Initialize failures to zero Initialize student to one While

26 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. 2002 Prentice Hall. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 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 33 34 Outline // Fig. 4. 11: Analysis. java // Analysis of examination results. // Java extension packages import javax. swing. JOption. Pane; 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 structure Line 31 // obtain result from user input = JOption. Pane. show. Input. Dialog( "Enter result (1=pass, 2=fail)" ); // convert result to int result = Integer. parse. Int( input ); // process result if ( result == 1 ) passes = passes + 1; else failures = failures + 1; 2002 Prentice Hall. All rights reserved. 27

35 36 37 38 39 40 41 42 43 44 45 46 47 48

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 + "n. Failed: " + failures; if ( passes > 8 ) output = output + "n. Raise Tuition"; JOption. Pane. show. Message. Dialog( null, output, "Analysis of Examination Results", JOption. Pane. INFORMATION_MESSAGE ); System. exit( 0 ); } // end method main // terminate application Analysis. java // end class Analysis 2002 Prentice Hall. All rights reserved. 28

29 4. 11 Assignment Operators • Assignment Operators – Abbreviate assignment expressions – Any

29 4. 11 Assignment Operators • Assignment Operators – Abbreviate assignment expressions – Any statement of form • 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 2002 Prentice Hall. All rights reserved.

30 2002 Prentice Hall. All rights reserved.

30 2002 Prentice Hall. All rights reserved.

31 4. 12 Increment and Decrement Operators • Unary increment operator (++) – Increment

31 4. 12 Increment and Decrement Operators • Unary increment operator (++) – Increment variable’s value by 1 • Unary decrement operator (--) – Decrement variable’s value by 1 • Preincrement / predecrement operator • Post-increment / post-decrement operator 2002 Prentice Hall. All rights reserved.

32 2002 Prentice Hall. All rights reserved.

32 2002 Prentice Hall. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 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 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 // 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 } c Line 13 postincrement Line 20 preincrement // end method main // end class Increment 5 5 6 6 33 2002 Prentice Hall. All rights reserved.

34 2002 Prentice Hall. All rights reserved.

34 2002 Prentice Hall. All rights reserved.

35 4. 13 Primitive Data Types • Primitive types – “building blocks” for more

35 4. 13 Primitive Data Types • Primitive types – “building blocks” for more complicated types • Java is strongly typed – All variables in a Java program must have a type • Java primitive types – portable across computer platforms that support Java 2002 Prentice Hall. All rights reserved.

36 2002 Prentice Hall. All rights reserved.

36 2002 Prentice Hall. All rights reserved.

4. 14 (Optional Case Study) Thinking About Objects: Identifying Class Attributes • Classes have

4. 14 (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 travel. Time • int travel. Time = 5; (in Java) 2002 Prentice Hall. All rights reserved. 37

38 2002 Prentice Hall. All rights reserved.

38 2002 Prentice Hall. All rights reserved.

39 Identifying Class Attributes (cont. ) • UML class diagram – Class attributes are

39 Identifying Class Attributes (cont. ) • UML class diagram – Class attributes are place in the middle compartment – Attributes are written language independently • e. g. , attribute open of class Elevator. Door – open : Boolean = false • May be coded in Java as – boolean open = false; 2002 Prentice Hall. All rights reserved.

40 Fig. 4. 18 Classes with attributes. 2002 Prentice Hall. All rights reserved.

40 Fig. 4. 18 Classes with attributes. 2002 Prentice Hall. All rights reserved.