Introduction To Computers and Programming: More Loops
Introduction To Computers and Programming: More Loops
2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.
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?
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?
Sentinels
However, what if we want the user or the input to decide when to end the program?
Use a sentinel
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
Using Sentinels contd 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" );
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.
Formulating Algorithms with Top-Down, Stepwise Refinement Refine the initialization phase from Initialize variables to:
Initialize total to zero Initialize counter to zero
Formulating Algorithms with Top-Down, Stepwise Refinement 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 average else Print No grades were entered
15
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
16
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 // Fig. 4.9: Average2.java // Class-average program with sentinel-controlled repetition. import java.text.DecimalFormat; // class to format numbers import javax.swing.JOptionPane; public class Average2 { public static void main( String args[] ) { int total; // sum of grades int gradeCounter; // number of grades entered int grade; // grade value double average; // number with decimal point for average // grade typed by user
Average2.java
String gradeString;
// initialization phase total = 0; // initialize total gradeCounter = 0; // initialize loop counter // processing phase // get first grade from user gradeString = JOptionPane.showInputDialog( "Enter Integer Grade or -1 to Quit:" ); // convert gradeString to int grade = Integer.parseInt( gradeString );
17
30 31 32 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 // loop until sentinel value read from user while ( grade != -1 ) { loop until gradeCounter total = total + grade; // add grade to total gradeCounter = gradeCounter + 1;equals sentinel value (-1) // increment counter // get next grade from user gradeString = JOptionPane.showInputDialog( "Enter Integer Grade or -1 to Quit:" ); // convert gradeString to int grade = Integer.parseInt( gradeString ); } // end while // termination phase
// if user entered at least one grade... if ( gradeCounter != 0 ) { // calculate average of all grades entered average = (double) total / gradeCounter; // display average with two digits of precision JOptionPane.showMessageDialog( null, "Class average is " + average , "Class Average", JOptionPane.INFORMATION_MESSAGE ); } // end if part of if...else
18
60 61 62 63 64 65 66 67 68 else // if no grades entered, output appropriate message JOptionPane.showMessageDialog( null, "No grades were entered", "Class Average", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); } // end main } // end class Average2 // terminate application
Average2.java
do/while Loop
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 );
4.8
action(s)
true
condition
false
23
false
Next Statement
24
Next Statement
Summary of Looping
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.
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.