1 / 63

Chapter 4 - Control Structures: Part 1

Chapter 4 - Control Structures: Part 1. Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 The if Selection Structure 4.6 The if/else Selection Structure 4.7 The while Repetition Structure

yuki
Download Presentation

Chapter 4 - Control Structures: Part 1

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 4 - Control Structures: Part 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 The if Selection Structure 4.6 The if/else Selection Structure 4.7 The while Repetition Structure 4.8 Formulating Algorithms: Case Study 1 (Counter-Controlled Repetition) 4.9 Formulating Algorithms with Top-Down, Stepwise Refinement: Case Study 2 (Sentinel-Controlled Repetition) 4.10 Formulating Algorithms with Top-Down, Stepwise Refinement: Case Study 3 (Nested Control Structures) 4.11 Assignment Operators 4.12 Increment and Decrement Operators 4.13 Primitive Data Types

  2. 4.1 Introduction • Before writing a program • Have a thorough understanding of problem • Carefully planned approach for solving it • While writing a program • Know what “building blocks” are available • Use good programming principles

  3. 4.2 Algorithms • Computing problems • All can be solved by executing a series of actions in a specific order • Algorithm • Procedure in terms of • actions to be executed • order in which these actions are to be executed • Example: "Rise and Shine" algorithm • Get out of bed, take off pajamas, take a shower, get dressed, eat breakfast, carpool to work • Program control • Specify order in which statements are to executed

  4. 4.3 Pseudocode • Pseudocode • Artificial, informal language • Helps develop algorithms • Similar to everyday English • Not actually executed on computers • “Think out” a program before writing it in a programming language • Easy to convert into a corresponding Java program • Consists only of executable statements • Declarations are not executable statements • Actions: input, output, calculation

  5. 4.4 Control Structures • Sequential execution • Statements executed one after the other in the order written • Transfer of control • Next statement executed is not the next one in sequence. • Overuse of goto in 1960'sled to many problems • Java does not have goto • Bohm and Jacopini • Demonstrated that all programs written in terms of 3 control structures • Sequence structure • Built into Java • Execute statements in order written

  6. 4.4 Control Structures • Bohm and Jacopini • Selection structures • Three types: if, if/else, and switch • Repetition structures • Three types: while, do/while, and for • Keywords • Words reserved for Java • Cannot be used as identifiers or variable names

  7. 4.4 Control Structures • Complete list of Java keywords

  8. 4.4 Control Structures • Flowchart • Graphical representation of an algorithm • Drawn using symbols connected by arrows called flowlines • Rectangle symbol (action symbol) • Indicates any type of action. • Oval symbol: • Indicates beginning or end of a program, or a section of code (circles) • When flowcharting a complete algorithm • Oval containing "Begin" is first symbol • Oval containing "End" is last symbol • When drawing a portion, small circles used • Useful for algorithms, but psuedocode generally preferred

  9. total = total + grade; add 1 to counter add grade to total counter = counter + 1; 4.4 Control Structures • Flowchart of sequence structure • Two actions performed in order

  10. 4.4 Control Structures • Single-entry/single-exit control structures • Connect exit point of one control structure to entry point of the next (control-structure stacking) • Makes programs easy to build • Control structure nesting • Only other way to connect control structures • Algorithms in Java • Constructed from seven types of control structures • Only two ways to combine them

  11. 4.5 The if Selection Structure • Selection structure • Used to choose among alternative courses of action • Pseudocode: If student’s grade is greater than or equal to 60 Print “Passed” • If condition true • Print statement executed and program goes on to next statement • If condition false • Print statement is ignored and the program goes onto the next statement • Indenting makes programs easier to read • Java ignores whitespace characters

  12. 4.5 The if Selection Structure • Selection structure • Psuedocode statement If student’s grade is greater than or equal to 60 Print “Passed” • Pseudocode statement in Java if ( studentGrade >= 60 ) System.out.println( "Passed" ); • Corresponds closely to pseudocode • Flowcharts • Diamond symbol - decision symbol • Important - indicates an decision is to be made • Contains expression that can be true or false

  13. true false print “Passed” grade >= 60 4.5 The if Selection Structure • Flowcharts • Diamond symbol has two paths • Indicates what to do if condition true or false • Decision can be made on anything that evaluates to a value of data type boolean • true or false Flowchart example of the if selection structure if is a single-entry/single-exit structure

  14. Note spacing/indentation conventions 4.6 The if/else Selection Structure • Selection structures • if • Only performs an action if condition true • if/else • Performs different action when condition true than when condition false • Psuedocode If student’s grade is greater than or equal to 60 Print “Passed”else Print “Failed” • Java code: if ( studentGrade >= 60 ) System.out.println( "Passed" ); else System.out.println( "Failed" );

  15. false true print “Passed” print “Failed” grade >= 60 4.6 The if/else Selection Structure • Flowchart of if/else structure • Note that only symbols (besides circles and arrows) are • Rectangles: actions • Diamonds: decisions • Action/decision model model of computing • Programmer's job to assemble structures by stacking and nesting, then the define actions and decisions

  16. 4.6 The if/else Selection Structure • Ternary conditional operator (?:) • Takes three arguments • Condition ? value if true: value if false • Our pseudocode could be written: System.out.println( studentGrade >= 60 ? “Passed” : “Failed” ); • Nested if/else structures • Test for multiple cases • Place if/else structures inside if/else structures • If first condition met, other statements skipped

  17. 4.6 The if/else Selection Structure • Nested structures if ( studentGrade >= 90 ) System.out.println( "A" );else if ( studentGrade >= 80 ) System.out.println( "B" ); else if ( studentGrade >= 70 ) System.out.println( "C" ); else if ( studentGrade >= 60 ) System.out.println( "D" ); else System.out.println( "F" ); else only executes when the if condition fails. Once a condition is met, the rest of the statements are skipped.

  18. 4.6 The if/else Selection Structure • Alternate form of nested structures • Avoids deep indentation • Generally preferred to previous format if ( grade >= 90 ) System.out.println( "A" );else if ( grade >= 80 ) System.out.println( "B" );else if ( grade >= 70 ) System.out.println( "C" );else if ( grade >= 60 ) System.out.println( "D" );else System.out.println( "F" ); As before, else only executes when the if condition fails.

  19. If x<= 5, nothing is output. 4.6 The if/else Selection Structure • Important note • Java always associates else with previous if unless braces ({}) present • Dangling-else problem if ( x > 5 ) if ( y > 5 ) System.out.println( "x and y are > 5" );else System.out.println( "x is <= 5" ); • Does not execute as it appears, executes as if ( x > 5 ) if ( y > 5 ) System.out.println( "x and y are > 5" ); else System.out.println( "x is <= 5" );

  20. 4.6 The if/else Selection Structure • Important note • Must force structure to execute as intended • Use braces to indicate that second if in body of first if ( x > 5 ) { if ( y > 5 ) System.out.println( "x and y are > 5" ); } else System.out.println( "x is <= 5" ); • Compound statements • Compound statement - set of statements within braces • Can be used wherever a single statement can • if expects one statement in its body • To enclose multiple statements, enclose them in braces

  21. 4.6 The if/else Selection Structure • Compound statements • Example: if (grade >= 60) System.out.println( "Passed" ); else { System.out.println( "Failed" ); System.out.println( "You must take this course again." );} • Without braces, second println always executes • Compound statements may contain declarations • Example: body of main • Called blocks (discussed in Chapter 6)

  22. 4.6 The if/else Selection Structure • Errors • Syntax errors • Caught by compiler • Example: forgetting a brace in a compound statement • Logic errors • Have effect at execution time • Non-fatal: program runs, but has incorrect output • Fatal: program exits prematurely

  23. 4.7 The while Repetition Structure • while repetition structure • Repeat an action while some condition remains true • Psuedocode: While there are more items on my shopping list Purchase next item and cross it off my list • while loop repeated until condition becomes false • First statement after repetition structure executed • Body may be a single or compound statement • If condition initially false then body never executed

  24. true product <= 1000 product = 2 * product false 4.7 The while Repetition Structure • Example int product = 2; while ( product <= 1000 ) product = 2 * product; • Flowchart

  25. 4.8 Formulating Algorithms: Case Study 1 (Counter-Controlled Repetition) • Illustrate how algorithms are developed • Consider class averaging problem • Problem statement: • A class of ten students took a quiz. The grades (integers in the range 0 to 100) for this quiz are available to you. Determine the class average on the quiz. • Counter-controlled repetition • Loop repeated until counter reaches a certain value • Definite repetition: number of repetitions known • We will use a counter to loop and input ten grades

  26. 4.8 Formulating Algorithms: Case Study 1 (Counter-Controlled Repetition) • Pseudocode Set total to zeroSet 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 tenPrint the class average • total - used to accumulate sum of a series of values • Should be initialized to zero to clear contents • counter - variable used to count • Show code, then discuss

  27. 1 // Fig. 4.7: Average1.java 2 // Class average program with counter-controlled repetition 3 import javax.swing.JOptionPane; 4 5 public class Average1 { 6 public static void main( String args[] ) 7 { 8 int total, // sum of grades 9 gradeCounter, // number of grades entered 10 gradeValue, // grade value 11 average; // average of all grades 12 String grade; // grade typed by user 13 14 // Initialization Phase 15 total = 0; // clear total 16 gradeCounter = 1; // prepare to loop 17 18 // Processing Phase 19 while ( gradeCounter <= 10 ) { // loop 10 times 20 21 // prompt for input and read grade from user 22 grade = JOptionPane.showInputDialog( 23 "Enter integer grade: " ); 24 25 // convert grade from a String to an integer 26 gradeValue = Integer.parseInt( grade ); 27 28 // add gradeValue to total 29 total = total + gradeValue; 30 Grade averaging application

  28. 34 35 // Termination Phase 36 average = total / 10; // perform integer division 37 38 // display average of exam grades 39 JOptionPane.showMessageDialog( 40 null, "Class average is " + average, "Class Average", 41 JOptionPane.INFORMATION_MESSAGE ); 42 43 System.exit( 0 ); // terminate the program 44 } 45 } 31 // add 1 to gradeCounter 32 gradeCounter = gradeCounter + 1; 33 } Program Output

  29. Program Output

  30. 3 import javax.swing.JOptionPane; 8 int total, // sum of grades 9 gradeCounter, // number of grades entered 10 gradeValue, // grade value 11 average; // average of all grades 12 String grade; // grade typed by user 4.8 Formulating Algorithms: Case Study 1 (Counter-Controlled Repetition) • Imports class JOptionPane • Used to read and write data via dialogs, as in Chapter 2 • Line 5: begin class Average1 • Line 6: begin method main • Every application class must define main • Declare variables • Declared in method main - local variables • Can only be used in the method that declares them • Variables must be declared before use

  31. 15 total = 0; // clear total 16 gradeCounter = 1; // prepare to loop 19 while ( gradeCounter <= 10 ) { // loop 10 times 22 grade = JOptionPane.showInputDialog( 23 "Enter integer grade: " ); 26 gradeValue = Integer.parseInt( grade ); 29 total = total + gradeValue; 4.8 Formulating Algorithms: Case Study 1 (Counter-Controlled Repetition) • Initialize variables • Using uninitialized local variables can cause errors • Loop while gradeCounter is less than or equal to 10 • Correspond to psuedocode "Input next grade" • Convert String to int • Update total

  32. 36 average = total / 10; // perform integer division 39 JOptionPane.showMessageDialog( 40 null, "Class average is " + average, "Class Average", 41 JOptionPane.INFORMATION_MESSAGE ); 43 System.exit( 0 ); // terminate the program 32 gradeCounter = gradeCounter + 1; 4.8 Formulating Algorithms: Case Study 1 (Counter-Controlled Repetition) • Increment gradeCounter • while condition eventually becomes false, loop ends • Calculates average, assigns to average • ints truncate remainder - solve in next section • Display average • Terminates application • Required if GUI used

  33. 1 // Fig. 4.7: Average1.java 2 // Class average program with counter-controlled repetition 3 import javax.swing.JOptionPane; 4 Braces enclose the body of the while loop (compound statement). 5 public class Average1 { 6 public static void main( String args[] ) 7 { 8 int total, // sum of grades 9 gradeCounter, // number of grades entered 10 gradeValue, // grade value 11 average; // average of all grades 12 String grade; // grade typed by user 13 14 // Initialization Phase 15 total = 0; // clear total 16 gradeCounter = 1; // prepare to loop 17 18 // Processing Phase 19 while ( gradeCounter <= 10 ) { // loop 10 times 20 21 // prompt for input and read grade from user 22 grade = JOptionPane.showInputDialog( 23 "Enter integer grade: " ); 24 25 // convert grade from a String to an integer 26 gradeValue = Integer.parseInt( grade ); 27 28 // add gradeValue to total 29 total = total + gradeValue; 30 1. import 2. Class Average1 3. main 4. Declare variables 4.1 Initialize variable 5. while loop 5.1 Input grade 5.2 Update total

  34. 34 35 // Termination Phase 36 average = total / 10; // perform integer division 37 38 // display average of exam grades 39 JOptionPane.showMessageDialog( 40 null, "Class average is " + average, "Class Average", 41 JOptionPane.INFORMATION_MESSAGE ); 42 43 System.exit( 0 ); // terminate the program 44 } 45 } 31 // add 1 to gradeCounter 32 gradeCounter = gradeCounter + 1; 33 } 5.2 Increment gradeCounter 6. Calculate average 7. Display results 8. System.exit( 0 ) Program Output

  35. Program Output

  36. 4.9 Formulating Algorithms with Top-Down, Stepwise Refinement: Case Study 2 (Sentinel-Controlled Repetition) • Generalize averaging problem Develop a class-averaging program that will process an arbitrary number of grades each time the program is run • Unknown number of students - how will the program end? • Sentinel value • Also called signal value/dummy value/flag value • Indicates “end of data entry” • Loop ends when sentinel input • Sentinel chosen so it cannot be a regular input • -1 in this case

  37. 4.9 Sentinel-Controlled Repetition • Top-down, stepwise refinement • Important for developing algorithms • Begin with a pseudocode representation of the top Determine the class average for the quiz • Complete representation of program • Top usually too general - must be refined • Divide top into a smaller tasks • First refinement Initialize variablesInput, sum and count the quiz gradesCalculate and print the class average

  38. 4.9 Sentinel-Controlled Repetition • Refine "Initialize variables" to Initialize total to zero Initialize counter to zero • Refine"Input, sum and count the quiz grades"to 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) • Refine "Calculate and print the class average"to If the counter is not equal to zero Set the average to the total divided by the counter Print the averageelse Print “No grades were entered”

  39. 4.9 Sentinel-Controlled Repetition • Many programs can be divided into three phases • Initialization • Initializes the program variables • Processing • Inputs data values and adjusts variables accordingly • Termination • Calculates and prints the final results • Helps breakup of programs for top-down refinement • Upcoming program • Use sentinel-controlled loop to calculate average • Show program, then discuss

  40. 1 // Fig. 4.9: Average2.java 2 // Class average program with sentinel-controlled repetition 3 import javax.swing.JOptionPane; 4 import java.text.DecimalFormat; 5 6 public class Average2 { 7 public static void main( String args[] ) 8 { 9 int gradeCounter, // number of grades entered 10 gradeValue, // grade value 11 total; // sum of grades 12 double average; // average of all grades 13 String input; // grade typed by user 14 15 // Initialization phase 16 total = 0; // clear total 17 gradeCounter = 0; // prepare to loop 18 19 // Processing phase 20 // prompt for input and read grade from user 21 input = JOptionPane.showInputDialog( 22 "Enter Integer Grade, -1 to Quit:" ); 23 24 // convert grade from a String to an integer 25 gradeValue = Integer.parseInt( input ); 26 27 while ( gradeValue != -1 ) { 28 // add gradeValue to total 29 total = total + gradeValue; 30 Application using a sentinel controlled loop

  41. 54 else 34 // prompt for input and read grade from user 35 input = JOptionPane.showInputDialog( 55 JOptionPane.showMessageDialog( null, 36 "Enter Integer Grade, -1 to Quit:" ); 56 "No grades were entered", "Class Average", 37 57 JOptionPane.INFORMATION_MESSAGE ); 38 // convert grade from a String to an integer 58 39 gradeValue = Integer.parseInt( input ); 59 System.exit( 0 ); // terminate the program 40 } 60 } 41 61 } 42 // Termination phase 43 DecimalFormat twoDigits = new DecimalFormat( "0.00" ); 44 45 if ( gradeCounter != 0 ) { 46 average = (double) total / gradeCounter; 47 48 // display average of exam grades 49 JOptionPane.showMessageDialog( null, 50 "Class average is " + twoDigits.format( average ), 51 "Class Average", 52 JOptionPane.INFORMATION_MESSAGE ); 53 } 31 // add 1 to gradeCounter 32 gradeCounter = gradeCounter + 1; 33 Application using a sentinel controlled loop

  42. Program Output

  43. 12 double average; // average of all grades 21 input = JOptionPane.showInputDialog( 22 "Enter Integer Grade, -1 to Quit:" ); 25 gradeValue = Integer.parseInt( input ); 4.9 Sentinel-Controlled Repetition • Much of the code similar to previous example • Concentrate on differences • Data type double • Can store floating-point (decimal) numbers • Input first grade

  44. 35 input = JOptionPane.showInputDialog( 36 "Enter Integer Grade, -1 to Quit:" ); Comments removed 39 gradeValue = Integer.parseInt( input ); 40 } 43 DecimalFormat twoDigits = new DecimalFormat( "0.00" ); 27 while ( gradeValue != -1 ) { 29 total = total + gradeValue; 32 gradeCounter = gradeCounter + 1; 4.9 Sentinel-Controlled Repetition • Next value checked before total incremented • DecimalFormat objects used to format numbers • 0 - format flag, specifies required digit position • This format - at least one digit to left of decimal, exactly two to right of decimal • 0's inserted if number does not meet requirements

  45. 43 DecimalFormat twoDigits = new DecimalFormat( "0.00" ); 45 if ( gradeCounter != 0 ) { 46 average = (double) total / gradeCounter; 4.9 Sentinel-Controlled Repetition • new - dynamic memory allocation operator • Creates an instance of an object • Value in parenthesis after type initializes the object • Cast operator (double) • Creates a floating-point copy of its operand (total) • Explicit conversion • Value in total still an integer • Arithmetic • Can only be performed between variables of same type • Promotion (implicit conversion) - promote a data type to another type

  46. 45 if ( gradeCounter != 0 ) { 46 average = (double) total / gradeCounter; 4.9 Sentinel-Controlled Repetition • Copy of total is a double • gradeCounter (an int) is promoted to a double • Division performed, result given to average • Cast operators • Available for all data types • Parenthesis around type name: (type) • Unary operator (one operand) - associates right to left • Floating point numbers • Not 100% accurate • Good approximation, fine for most applications • 10/3 = 3.333333... • Finite precision

  47. 49 JOptionPane.showMessageDialog( null, 50 "Class average is " + twoDigits.format( average ), 51 "Class Average", 52 JOptionPane.INFORMATION_MESSAGE ); 4.9 Sentinel-Controlled Repetition • Use method format to output the formatted number • Using "0.00" format

  48. 1 // Fig. 4.9: Average2.java 2 // Class average program with sentinel-controlled repetition 3 import javax.swing.JOptionPane; 4 import java.text.DecimalFormat; 5 6 public class Average2 { 7 public static void main( String args[] ) 8 { 9 int gradeCounter, // number of grades entered Test for sentinel value. 10 gradeValue, // grade value 11 total; // sum of grades 12 double average; // average of all grades 13 String input; // grade typed by user 14 15 // Initialization phase 16 total = 0; // clear total 17 gradeCounter = 0; // prepare to loop 18 19 // Processing phase 20 // prompt for input and read grade from user 21 input = JOptionPane.showInputDialog( 22 "Enter Integer Grade, -1 to Quit:" ); 23 24 // convert grade from a String to an integer 25 gradeValue = Integer.parseInt( input ); 26 27 while ( gradeValue != -1 ) { 28 // add gradeValue to total 29 total = total + gradeValue; 30 1. import 2. Class Average2 2.1 main 3. while loop

  49. 54 else 34 // prompt for input and read grade from user 35 input = JOptionPane.showInputDialog( 55 JOptionPane.showMessageDialog( null, 36 "Enter Integer Grade, -1 to Quit:" ); 56 "No grades were entered", "Class Average", 37 57 JOptionPane.INFORMATION_MESSAGE ); Output the formatted number. Cast total to a double. 58 38 // convert grade from a String to an integer 59 System.exit( 0 ); // terminate the program 39 gradeValue = Integer.parseInt( input ); 40 } 60 } 61 } 41 42 // Termination phase 43 DecimalFormat twoDigits = new DecimalFormat( "0.00" ); 44 45 if ( gradeCounter != 0 ) { 46 average = (double) total / gradeCounter; 47 48 // display average of exam grades 49 JOptionPane.showMessageDialog( null, 50 "Class average is " + twoDigits.format( average ), 51 "Class Average", 52 JOptionPane.INFORMATION_MESSAGE ); 53 } 31 // add 1 to gradeCounter 32 gradeCounter = gradeCounter + 1; 33 3. while loop 4. DecimalFormat

  50. Program Output

More Related