introduction to computers and programming more loops 2000 prentice hall, inc. all rights reserved....

27
Introduction to Computers and Programming More Loops 2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.

Post on 15-Jan-2016

218 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course

Introduction to Computers and Programming

More Loops

2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.

Page 2: Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course

review

• What are three ways to rewrite:x = x + 1;

• What are the three elements of a while loop?• What is the difference between pre and post

increment operators?• Are you guaranteed to execute the body of a while

loop at all?• What is an infinite loop?• True or False: You never want to use an infinite

loop?

Page 3: Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course

3

Review

• Given:char c = 'a';

c++;

What is the value of variable c?• What method do you use to extract characters

from a String?– How would you use that method to get the first character

from a String?

Page 4: Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course

Sentinels

Page 5: Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course

Sentinel-controlled repetition

• Counter Controlled Repetition:– Simply means that we use a counter to tell you when to stop

repeating a statement or group of statements

– The examples from last class were counter-controlled repetition

• However, what if we want the user or the input to decide when to end the program?– Use a sentinel

Page 6: Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course

Understanding Sentinels

• Sentinel: a special value that indicates the “end of data entry.”

• Also known as signal value, dummy value, or flag value

• For example:– -1 means end of data.– 0 means end of data.– "END" means ends of data– Depends on the specific application you are building.

• With a sentinel, we have an indefinite repetition, because the number of repetitions is unknown at the time we write the program (or start the loop).

2000 Prentice Hall, Inc. All rights reserved. Modified by Evan Korth

Page 7: Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course

Using Sentinels

• How are they used?– Programmer picks a value that would never be encountered

for normal data

– User enters normal data and then when done, enters the unusual value

– The loop will stop when seeing the unusual value

Page 8: Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course

Using Sentinels cont’d

• For example, if entering age for people, you could pick a sentinel of –1

• No one would expect to be –1 year old.

• It is a good practice is to remind the user in each iteration of the loop what the sentinel value is– For example,

(" Enter the age of the current resident or –1 to end" );

Page 9: Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course

Good Programming tips

• Pick a sentinel value that you are CERTAIN will never be confused with normal data

• Style: Remind user each iteration what the sentinel is

• Y2K-like problem– Programmers often used 9999 as a sentinel to end a loop

– Worry that on September 9, 1999 (sometimes abbreviated 9999) programs would erroneously stop executing before they were supposed to.

Page 10: Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course

Case Study: Using Sentinel Controlled Loops

Page 11: Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course

Formulating Algorithms with Top-Down, Stepwise Refinement

• Problem becomes: 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 know to end?

• Use sentinel value – Loop ends when user inputs the sentinel value

– Sentinel value chosen so it cannot be confused with a regular input (such as -1 in this case)

2000 Prentice Hall, Inc. All rights reserved.

Page 12: Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course

Formulating Algorithms with Top-Down, Stepwise Refinement

• Top-down, stepwise refinement – Begin with a pseudocode representation of the top:

Determine the class average for the quiz

– Divide top into smaller tasks and list them in order: Initialize variablesInput, sum and count the quiz gradesCalculate and print the class average

• Many programs have three phases:– Initialization: initializes the program variables

– Processing: inputs data values and adjusts program variables accordingly

– Termination: calculates and prints the final results

2000 Prentice Hall, Inc. All rights reserved.

Page 13: Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course

Formulating Algorithms with Top-Down, Stepwise Refinement

• Refine the initialization phase from Initialize variables to:

Initialize 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 total Add one to the grade counter Input the next grade (possibly the sentinel)

2000 Prentice Hall, Inc. All rights reserved.

Page 14: Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course

Formulating Algorithms with Top-Down, Stepwise Refinement

• Refine Calculate and print the class average toIf 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”

2000 Prentice Hall, Inc. All rights reserved.

Page 15: Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course

15

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

If the counter is not equal to zeroSet the average to the total divided by the counterPrint the average

elsePrint “No grades were entered”

Class-average problem pseudocode algorithm with sentinel-controlled repetition.

2003 Prentice Hall, Inc. All rights reserved.

Page 16: Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course

2003 Prentice Hall, Inc.All rights reserved.

16

Average2.java

1 // Fig. 4.9: Average2.java2 // Class-average program with sentinel-controlled repetition.3 import java.text.DecimalFormat; // class to format numbers4 import javax.swing.JOptionPane;5 6 public class Average2 {7 8 public static void main( String args[] )9 {10 int total; // sum of grades11 int gradeCounter; // number of grades entered12 int grade; // grade value13 14 double average; // number with decimal point for average15 16 String gradeString; // grade typed by user17 18 // initialization phase19 total = 0; // initialize total20 gradeCounter = 0; // initialize loop counter21 22 // processing phase23 // get first grade from user 24 gradeString = JOptionPane.showInputDialog(25 "Enter Integer Grade or -1 to Quit:" );26 27 // convert gradeString to int 28 grade = Integer.parseInt( gradeString ); 29

Page 17: Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course

2003 Prentice Hall, Inc.All rights reserved.

1730 // loop until sentinel value read from user31 while ( grade != -1 ) { 32 total = total + grade; // add grade to total33 gradeCounter = gradeCounter + 1; // increment counter34 35 // get next grade from user 36 gradeString = JOptionPane.showInputDialog(37 "Enter Integer Grade or -1 to Quit:" );38 39 // convert gradeString to int 40 grade = Integer.parseInt( gradeString ); 41 42 } // end while43 44 // termination phase45 46 47 // if user entered at least one grade...48 if ( gradeCounter != 0 ) {49 50 // calculate average of all grades entered51 average = (double) total / gradeCounter; 52 53 // display average with two digits of precision54 JOptionPane.showMessageDialog( null,55 "Class average is " + average ,56 "Class Average", JOptionPane.INFORMATION_MESSAGE );57 58 } // end if part of if...else59

loop until gradeCounter equals sentinel value (-1)

Page 18: Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course

2003 Prentice Hall, Inc.All rights reserved.

18

Average2.java

60 else // if no grades entered, output appropriate message61 JOptionPane.showMessageDialog( null, "No grades were entered",62 "Class Average", JOptionPane.INFORMATION_MESSAGE );63 64 System.exit( 0 ); // terminate application65 66 } // end main67 68 } // end class Average2

Page 19: Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course

do/while Loop

Page 20: Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course

The do/while Repetition Structure

• The do/while repetition structure – Similar to the while structure

– Condition for repetition tested after the body of the loop is performed

• All actions are performed at least once

– Format:do {

statement(s);

} while ( condition );

 

Page 21: Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course

4.8 The do/while Repetition Structure

• Flowchart of the do/while repetition structure

true

false

action(s)

condition

Page 22: Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course

Keywords: break and continue

Page 23: Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course

23

Using the Keywords break and continue

Page 24: Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course

24

The continue Keyword

Page 25: Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course

Summary of Looping

Page 26: Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course

Summary of Looping

• Two broad types of loops:– Counter-controlled repetition

• A counter controls the number of repetitions.

• Also known as a definite repetition, because we know in advance how many times the loop will be executed.

– Sentinel-controlled repetition• A sentinel controls the number of repetitions

• Also known as indefinite repetition, because we do not know in advance how many times the loop will be executed.

• In either case, watch out for infinite loops!• If your program requires some kind of loop, first

determine which kind of loop you want.

Page 27: Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course

Summary of Looping

• Once you know which kind of loop you want, determine which while loop you want:– While loops

• condition is tested first; then action occurs.

• While loops are much more common than do/while loops.

– Do/while loops• action is run first; then, condition is tested.

• Use this if you want to make sure that your loop is guaranteed to be run at least once.