63
2000 Prentice Hall, Inc. All rights reserved. 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

2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

Embed Size (px)

Citation preview

Page 1: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

1

Chapter 4 - Control Structures: Part 1

Outline4.1 Introduction4.2 Algorithms4.3 Pseudocode4.4 Control Structures4.5 The if Selection Structure4.6 The if/else Selection Structure4.7 The while Repetition Structure4.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 Operators4.12 Increment and Decrement Operators4.13 Primitive Data Types

Page 2: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

2

4.1 Introduction

• Before writing program– Have thorough understanding of problem

– Carefully planned approach for solving it

• While writing program– Know what “building blocks” are available

– Use good programming principles

Page 3: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

3

4.2 Algorithms

• Computing problems – 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 to execute statements

Page 4: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

4

4.3 Pseudocode

• Pseudocode– Artificial, informal language

• Helps develop algorithms

– Similar to everyday English

– Not actually executed on computers

– “Think out” program before writing it

– Easy to convert into corresponding Java program• Consists only of executable statements

– Declarations are not executable statements

– Actions: input, output, calculation

Page 5: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

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's led 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

Page 6: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

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

Page 7: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

7

4.4 Control Structures

J ava Keywords

abstract boolean break byte case

catch char class continue default do double else extends false final finally float for if implements import instanceof int interface long native new null package private protected public return short static super switch synchronized this throw throws transient true try void volatile while

Keywords that are reserved but not used by Java const goto

• Complete list of Java keywords

Page 8: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

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

Page 9: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

9

4.4 Control Structures

• Flowchart of sequence structure– Two actions performed in order

total = total + grade;add grade to total

add 1 to counter counter = counter + 1;

Page 10: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

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

Page 11: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

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 60Print “Passed”

– If condition true • Print statement executed

• Go on to next statement

– If condition false • Print statement is ignored

• Go on to next statement

– Indenting makes programs easier to read• Java ignores whitespace characters

Page 12: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

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" );

• Notice similiarity

• Flowcharts– Diamond symbol - decision symbol

• Important - indicates an decision is to be made

• Contains expression that can be true or false

Page 13: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

13

4.5 The if Selection Structure

• Flowcharts– Diamond symbol has two paths

• Actions if conditions true or false

– Decision can be made on anything that evaluates to a value of data type boolean• true or false

true

false

grade >= 60

print “Passed”

 

Flowchart example of the if selection structure

if is a single-entry/single-exit structure

Page 14: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

14

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

• PsuedocodeIf 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" );

Note spacing/indentation conventions

Page 15: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

15

4.6 The if/else Selection Structure

• Flowchart of if/else structure– Symbols (besides circles and arrows)

• Rectangles: actions

• Diamonds: decisions

– Action/decision model model of computing• Programmer assemble structures by stacking and nesting

• Then defines actions and decisions

truefalse

print “Failed” print “Passed”

grade >= 60

Page 16: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

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

Page 17: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

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 condition is met, rest of statements skipped.

Page 18: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

18

4.6 The if/else Selection Structure

• Alternate form of nested structures– Avoids deep indentation

– 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.

Page 19: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

19

4.6 The if/else Selection Structure

• Important note– Java 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" );

If x <= 5, nothing is output.

Page 20: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

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– 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

Page 21: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

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, third println always executes

– Compound statements may contain declarations• Example: body of main• Called blocks (discussed in Chapter 6)

Page 22: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

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

Page 23: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

23

4.7 The while Repetition Structure

• while repetition structure– Repeat 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, body never executed

Page 24: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

24

4.7 The while Repetition Structure

• Exampleint product = 2;

while ( product <= 1000 ) product = 2 * product;

• Flowchart

product <= 1000 product = 2 * producttrue

false

Page 25: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

254.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

– Use a counter to loop and input ten grades

Page 26: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

264.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 tenInput the next gradeAdd the grade into the totalAdd 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

• Initialize to zero to clear contents

– Counter - variable used to count

– Show code, then discuss

Page 27: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

Outline27

Grade averaging application

1 // Fig. 4.7: Average1.java2 // Class average program with counter-controlled repetition3 import javax.swing.JOptionPane;45 public class Average1 {6 public static void main( String args[] ) 7 {8 int total, // sum of grades9 gradeCounter, // number of grades entered10 gradeValue, // grade value11 average; // average of all grades12 String grade; // grade typed by user13 14 // Initialization Phase15 total = 0; // clear total16 gradeCounter = 1; // prepare to loop17 18 // Processing Phase19 while ( gradeCounter <= 10 ) { // loop 10 times2021 // prompt for input and read grade from user22 grade = JOptionPane.showInputDialog(23 "Enter integer grade: " );2425 // convert grade from a String to an integer26 gradeValue = Integer.parseInt( grade );2728 // add gradeValue to total29 total = total + gradeValue; 30

Page 28: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

Outline28

Program Output

31 // add 1 to gradeCounter

32 gradeCounter = gradeCounter + 1;

33 }

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 }

Page 29: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

Outline29

Program Output

Page 30: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

304.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

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

Page 31: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

314.8 Formulating Algorithms: Case Study 1 (Counter-Controlled

Repetition)

– Initialize variables• Using uninitialized local variables can cause errors

– while loop

– Correspond to psuedocode "Input next grade"

– Convert String to int

– Update total

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;

Page 32: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

324.8 Formulating Algorithms: Case Study 1 (Counter-Controlled

Repetition)

– Increment gradeCounter • while condition eventually becomes false, loop ends

– Calculates average • ints truncate remainder - solve in next section

– Display average

– Terminates application• Required if GUI used

32 gradeCounter = gradeCounter + 1;

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

Page 33: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

Outline33

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

1 // Fig. 4.7: Average1.java2 // Class average program with counter-controlled repetition3 import javax.swing.JOptionPane;45 public class Average1 {6 public static void main( String args[] ) 7 {8 int total, // sum of grades9 gradeCounter, // number of grades entered10 gradeValue, // grade value11 average; // average of all grades12 String grade; // grade typed by user13 14 // Initialization Phase15 total = 0; // clear total16 gradeCounter = 1; // prepare to loop17 18 // Processing Phase

1919 while ( gradeCounter <= 10 ) { // loop 10 times2021 // prompt for input and read grade from user22 grade = JOptionPane.showInputDialog(23 "Enter integer grade: " );2425 // convert grade from a String to an integer26 gradeValue = Integer.parseInt( grade );2728 // add gradeValue to total29 total = total + gradeValue; 30

Braces enclose the body of the while loop (compound statement).

Page 34: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

Outline34

5.2 Increment gradeCounter

6. Calculate average

7. Display results

8. System.exit( 0 )

Program Output

31 // add 1 to gradeCounter

32 gradeCounter = gradeCounter + 1;

33 }

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 }

Page 35: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

Outline35

Program Output

Page 36: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

36

4.9 Sentinel-Controlled Repetition

• Generalize averaging problemDevelop 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

Page 37: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

37

4.9 Sentinel-Controlled Repetition

• Top-down, stepwise refinement– Important for developing algorithms

– Begin with pseudocode representation of the topDetermine the class average for the quiz

• Complete representation of program

– Top usually too general - must be refined• Divide top into smaller tasks

– First refinementInitialize variablesInput, sum and count the quiz gradesCalculate and print the class average

Page 38: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

38

4.9 Sentinel-Controlled Repetition

• Refine "Initialize variables" toInitialize total to zeroInitialize 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 totalAdd one to the grade counterInput the next grade (possibly the sentinel)

• Refine "Calculate and print the class average" toIf the counter is not equal to zero

Set the average to the total divided by the counterPrint the average

elsePrint “No grades were entered”

Page 39: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

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

Page 40: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

Outline40

Application using a sentinel controlled loop

1 // Fig. 4.9: Average2.java2 // Class average program with sentinel-controlled repetition3 import javax.swing.JOptionPane;

4 import java.text.DecimalFormat;56 public class Average2 {7 public static void main( String args[] )8 {9 int gradeCounter, // number of grades entered10 gradeValue, // grade value11 total; // sum of grades12 double average; // average of all grades13 String input; // grade typed by user1415 // Initialization phase16 total = 0; // clear total17 gradeCounter = 0; // prepare to loop18 19 // Processing phase20 // prompt for input and read grade from user

21 input = JOptionPane.showInputDialog(22 "Enter Integer Grade, -1 to Quit:" );2324 // convert grade from a String to an integer25 gradeValue = Integer.parseInt( input );2627 while ( gradeValue != -1 ) {28 // add gradeValue to total29 total = total + gradeValue;30

Page 41: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

Outline41

Application using a sentinel controlled loop

34 // prompt for input and read grade from user35 input = JOptionPane.showInputDialog(36 "Enter Integer Grade, -1 to Quit:" );3738 // convert grade from a String to an integer39 gradeValue = Integer.parseInt( input );40 }4142 // Termination phase43 DecimalFormat twoDigits = new DecimalFormat( "0.00" );4445 if ( gradeCounter != 0 ) {46 average = (double) total / gradeCounter; 4748 // display average of exam grades49 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

54 else55 JOptionPane.showMessageDialog( null,56 "No grades were entered", "Class Average",57 JOptionPane.INFORMATION_MESSAGE );5859 System.exit( 0 ); // terminate the program60 }61 }

Page 42: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

Outline42

Program Output

Page 43: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

43

4.9 Sentinel-Controlled Repetition

– Much of code similar to previous example• Concentrate on differences

– Data type double• Can store floating-point (decimal) numbers

– Input first grade

12 double average; // average of all grades

21 input = JOptionPane.showInputDialog(

22 "Enter Integer Grade, -1 to Quit:" );

25 gradeValue = Integer.parseInt( input );

Page 44: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

44

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

27 while ( gradeValue != -1 ) {

29 total = total + gradeValue;

32 gradeCounter = gradeCounter + 1;

35 input = JOptionPane.showInputDialog(36 "Enter Integer Grade, -1 to Quit:" );

39 gradeValue = Integer.parseInt( input );

40 }

Comments removed

43 DecimalFormat twoDigits = new DecimalFormat( "0.00" );

Page 45: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

45

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

43 DecimalFormat twoDigits = new DecimalFormat( "0.00" );

45 if ( gradeCounter != 0 ) {

46 average = (double) total / gradeCounter;

Page 46: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

46

4.9 Sentinel-Controlled Repetition

– Copy of total is a double • gradeCounter (an int) is promoted to a double

– 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

45 if ( gradeCounter != 0 ) {

46 average = (double) total / gradeCounter;

Page 47: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

47

4.9 Sentinel-Controlled Repetition

– Use method format to output the formatted number• Using "0.00" format

49 JOptionPane.showMessageDialog( null,

50 "Class average is " + twoDigits.format( average ),

51 "Class Average",

52 JOptionPane.INFORMATION_MESSAGE );

Page 48: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

Outline48

1. import

2. Class Average2

2.1 main

3. while loop

1 // Fig. 4.9: Average2.java2 // Class average program with sentinel-controlled repetition3 import javax.swing.JOptionPane;

4 import java.text.DecimalFormat;56 public class Average2 {7 public static void main( String args[] )8 {9 int gradeCounter, // number of grades entered10 gradeValue, // grade value11 total; // sum of grades12 double average; // average of all grades13 String input; // grade typed by user1415 // Initialization phase16 total = 0; // clear total17 gradeCounter = 0; // prepare to loop18 19 // Processing phase20 // prompt for input and read grade from user

21 input = JOptionPane.showInputDialog(22 "Enter Integer Grade, -1 to Quit:" );2324 // convert grade from a String to an integer25 gradeValue = Integer.parseInt( input );26

2727 while ( gradeValue != -1 ) {28 // add gradeValue to total29 total = total + gradeValue;30

Test for sentinel value.

Page 49: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

Outline49

3. while loop

4. DecimalFormat

34 // prompt for input and read grade from user35 input = JOptionPane.showInputDialog(36 "Enter Integer Grade, -1 to Quit:" );3738 // convert grade from a String to an integer39 gradeValue = Integer.parseInt( input );40 }4142 // Termination phase43 DecimalFormat twoDigits = new DecimalFormat( "0.00" );4445 if ( gradeCounter != 0 ) {

4646 average = (double) total / gradeCounter; 4748 // display average of exam grades49 JOptionPane.showMessageDialog( null,

5050 "Class average is " + twoDigits.format( average ),51 "Class Average",52 JOptionPane.INFORMATION_MESSAGE );53 }

31 // add 1 to gradeCounter

32 gradeCounter = gradeCounter + 1;

33

54 else55 JOptionPane.showMessageDialog( null,56 "No grades were entered", "Class Average",57 JOptionPane.INFORMATION_MESSAGE );5859 System.exit( 0 ); // terminate the program60 }61 }

Cast total to a double.

Output the formatted number.

Page 50: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

Outline50

Program Output

Page 51: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

51

4.10Nested Control Structures

• Problem statement– A college has a list of test results (1 = pass, 2 = fail) for a

licensing exam for 10 students. Write a program that analyzes the results. If more than 8 students pass, print "Raise Tuition".

– Program should analyze results as follows:• Input each test result (1 or 2). Display message "Enter result"

on screen each time program requests another result.

• Count number of results of each type

• Display summary of test results - indicate how many students passed and how many failed

• If more than 8 passed, print "Raise tuition"

Page 52: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

52

4.10 Nested Control Structures

• Observations– Program must process 10 test results

• Use counter-controlled loop

– Two counters can be used• One for passes, one for fails

– Each test result is either a 1 or a 2 • If not a 1, assume it is a 2

– Must decide if more than 8 passes

• Psuedocode representation of top– Analyze exam results and decide if tuition should be raised

– Top complete representation of problem• May need several refinements

Page 53: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

53

4.10 Nested Control Structures

• First refinementInitialize variables

Input the ten quiz grades and count passes and failures

Print a summary of the exam results and decide if tuition should be raised

– Refine "Initialize variables" to Initialize passes to zeroInitialize failures to zeroInitialize student counter to one

Page 54: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

54

4.10 Nested Control Structures

– Refine "Input the ten quiz grades and count passes and failures" to

While student counter is less than or equal to tenInput the next exam result

If the student passed

Add one to passeselse Add one to failures

Add one to student counter

Page 55: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

55

4.10 Nested Control Structures

– Refine "Print a summary of the exam results and decide if tuition should be raised" toPrint the number of passesPrint the number of failures

If more than eight students passed Print “Raise tuition”

• Psuedocode sufficiently refined– Can be converted to a Java program

Page 56: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

Outline56

1. import

2. Class Analysis

3. main

3.1 Initialize variables

4. while loop

5. Display results

1 // Fig. 4.11: Analysis.java2 // Analysis of examination results.3 import javax.swing.JOptionPane;45 public class Analysis {6 public static void main( String args[] ) 7 {8 // initializing variables in declarations9 int passes = 0, // number of passes10 failures = 0, // number of failures11 student = 1, // student counter12 result; // one exam result13 String input, // user-entered value14 output; // output string1516 // process 10 students; counter-controlled loop17 while ( student <= 10 ) {18 input = JOptionPane.showInputDialog(19 "Enter result (1=pass,2=fail)" );20 result = Integer.parseInt( input );212222 if ( result == 1 )23 passes = passes + 1;24 else25 failures = failures + 1;2627 student = student + 1;28 }2930 // termination phase31 output = "Passed: " + passes +32 "\nFailed: " + failures;

Increment appropriate counter depending on input.

Page 57: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

Outline57

5. Display results

Program Output

33

3434 if( passes > 8 )

35 output = output + "\nRaise Tuition";

36

37 JOptionPane.showMessageDialog( null, output,

38 "Analysis of Examination Results",

39 JOptionPane.INFORMATION_MESSAGE );

40

41 System.exit( 0 );

42 }

43}

Check whether to raise tuition.

9 passes

1 fail

Page 58: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

58

4.11Assignment Operators

• Assignment operators– Abbreviate assignment expressions

c = c + 3; abbreviated as c += 3; – Uses addition assignment operator.

• Statements of the formvariable = variable operator expression;

can be rewritten asvariable operator= expression;

• Other examples d -= 4 (d = d - 4)

e *= 5 (e = e * 5)f /= 3 (f = f / 3)g %= 9 (g = g % 9)

Page 59: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

59

4.12Increment and Decrement Operators

• Other operators– Increment operator (++)

• Can be used instead of c += 1

– Decrement operator (--)• Can be used instead of c -= 1

• Pre/post– Preincrement/predecrement

• Operator before variable, i.e. ++c or --c• Change variable, then surrounding expression evaluated

– Postincrement/postdecrement• Operator after variable, i.e. c++ or c--• Variable changes, then surrounding expression evaluated

Page 60: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

60

4.12Increment and Decrement Operators

• If variable not in an expression– Pre and post forms have the same effect

c++; same as ++c;

• Upcoming program– Show differences between pre and post forms

Page 61: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

Outline61

1. Class Increment

2. main

3. Initialize variable

3.1 postincrement

3.2 preincrement

1// Fig. 4.14: Increment.java

2// Preincrementing and postincrementing

3

4public class Increment {

5 public static void main( String args[] )

6 {

7 int c;

8

9 c = 5;

10 System.out.println( c ); // print 5

1111 System.out.println( c++ ); // print 5 then postincrement

12 System.out.println( c ); // print 6

13

14 System.out.println(); // skip a line

15

16 c = 5;

17 System.out.println( c ); // print 5

18 System.out.println( ++c ); // preincrement then print 6

19 System.out.println( c ); // print 6

20 }

21}

556 566

Expression evaluated (println), then variable incremented.

Variable incremented, then expression evaluated (println).

Page 62: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

62

4.13Primitive Data Types

• Primitive data types– char, byte, short, int, long, float, double, boolean

– Building blocks for more complicated types• Variables must have type before use

• Strongly typed language

– Primitive types portable, unlike C and C++• In C/C++, write different versions of programs

– Data types not guaranteed to be identical– ints may be 2 or 4 bytes, depending on system

• WORA - Write once, run anywhere

– Default values• boolean gets false, all other types are 0

Page 63: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control

2000 Prentice Hall, Inc. All rights reserved.

63

4.13Primitive Data Types

Type Size in bits

Values Standard

boolean 8 true or false

char 16 ’\u0000’ to ’\uFFFF’ (ISO Unicode character set)

byte 8 –128 to +127

short 16 –32,768 to +32,767

int 32 –2,147,483,648 to +2,147,483,647

long 64 –9,223,372,036,854,775,808 to +9,223,372,036,854,775,807

float 32 –3.40292347E+38 to +3.40292347E+38

(IEEE 754 floating point)

double 64

–1.79769313486231570E+308 to +1.79769313486231570E+308

(IEEE 754 floating point)