Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Sentinel Loops

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 22

Sentinel Controlled Loops

Say that a program is to add up a list of numbers entered from the keyboard. Will a loop be used in this program? Answer..yes: A counting loop could do this if the user first said how many integers were in the list. But often users don't know this in advance so, what do we do?

The idea of a sentinel controlled loop is that there is a special value (the sentinel) that is used to say when the loop is done. In this example, the user enters a zero when the sum is complete. Zero is the sentinel. Here is how the program should work: C:\Enter first integer (enter 0 to quit): 1 Enter an integer (or 0 to quit): -3 Enter an integer (or 0 to quit): 4 Enter an integer (or 0 to quit): 0 Sum of the integers: 2

The flow chart

Partially completed program


import java.util.Scanner; class AddUpNumbers { public static void main (String[] args ) { Scanner scan = new Scanner( System.in ); int value; // data entered by the user int sum = 0; // initialize the sum // get the first value System.out.print( "Enter first integer (enter 0 to quit): " ); value = scan.nextInt(); while ( value != 0 ) { ------------------------//add value to sum ; //get the ext value from the user -------------------- ; } System.out.println( "Sum of the integers: " + sum ); }}

System.out.print( "Enter first integer (enter 0 to quit): " ); value = scan.nextInt(); while ( value != 0 ) { //add value to sum sum = sum + value; //get the next value from the user System.out.println( "Enter next integer (enter 0 to quit):" ); value = scan.nextInt(); } System.out.println( "Sum of the integers: " + sum ); } } Questions: What would happen if the user entered 0 first time?

What if we wanted to modify the program so that it prompts the user with the following: Enter the 2nd integer (enter 0 to quit): Enter the 3rd integer (enter 0 to quit): Enter the 4th integer (enter 0 to quit): Enter the 5th integer (enter 0 to quit): Enter the 6th integer (enter 0 to quit): .... and so on .... Enter the 20th integer (enter 0 to quit): Enter the 21th integer (enter 0 to quit): The prompt shows poor grammar for integers 21, 22, 23, 31, 32, 33 and so on. Let us regard this as acceptable.

Just to remind you.

So .what do we need to do
Change the output line
System.out.println( "Enter the " + (count+1) + suffix + " integer (enter 0 to quit):" );

We have three choices


To make a three-way choice, a nested if is used. This is where an if-else statement is part of a the true-branch (or false-branch) of another if-else statement. So the nested if-else will execute only when the outer ifelse has already made a choice between two branches. Here is a program fragment that makes a choice of one of the three suffixes.

Program fragment String suffix; int count=0; // count is the number of integers added so far. // count+1 is the next integer to read // While goes here .... if ( count+1 __________ ) suffix = "nd"; else if ( count+1 ___________ ) // false-branch of first if suffix = "rd"; // false-branch of first if else // false-branch of first if suffix = "th"; // false-branch of first if System.out.println( "Enter the " + (count+1) + suffix + " integer (enter 0 to quit):" );

Matching if's and else's

Start with the first if and work downward. Each else matches the closest previous unmatched if. An if matches only one else and an else matches only one if.

Here is another example. It is not indented properly. Use the rule to figure out which ifs and ifs match.
if ( a == if ( d == total = else total = else total = b ) e ) 0; total + a; total + b;

Make Matches clear with Braces


In this case, the braces are not really needed, but are probably a good idea, for clarity:
if ( a == b ) { if ( d == e ) total = 0; else total = total + b; }

New Example
Sometimes the user is asked explicitly if the loop should continue. The user enters "yes" or "no" (or maybe "y" or "n"). Now the sentinel is of type String or char. The next example illustrates this: Say that you are interested in the value of the polynomial:

7x3- 3x2 + 4x - 12 or various values of x. The value x is a double precision value. For example, when x == 2.0 the polynomial is equal to:
7*23- 3*22 + 4*2 - 12 = 7*8 - 3*4 + 8 - 12 = 40
The program lets the user enter various values for x and see the result for each one.

Testing the User's Response


class EvalPoly { public static void main (String[] args ) { double x; // a value to use with the polynomial String response = "y"; // "y" or "n while ( response.equals("y") ) { // Get a value for x. // Evaluate the polynomial. // Print out the result. // Ask the user if the program should continue. // The user's answer is "response". } }}

The condition part of the while statement, response.equals("y") evaluates to true or false. Here is how this happens:
response is a reference to a String object. A String object has both data and methods (as do all objects). The data part of response is the characters the user types. response has an equals() method that tests if another string is equal to it. response.equals("y") tests if the String response is equal to the String "y". The result of the test is true or false.

So, what all do I need


As with all loops, there were three things to get right: Initializing the loop. Testing if the loop should continue. Setting up for the next test.

import java.io.*; class EvalPoly { public static void main (String[] args ) { Scanner scan = new Scanner ( System.in ); double x; // a value to use with the polynomial double result; // result of evaluation String response = "y"; // "y" or "n" while ( response.equals( "y" ) ) { // Get a value for x. System.out.println("Enter a value for x:") ; x = scan _______________; // Evaluate the polynomial. result = (whats the formula)__________; // Print out the result. System.out.println _______________________________; // Ask the user if the program should continue. System.out.println("continue (y or n)?"); response = scan.nextLine(); } } }

Questions: match the ifs.


If ( val == 34 ) { sum = sum + val; val = 0; next= 5; } else { sum = sum - val; if ( sum < limit ) flag = true; else flag = false; }

IF ( val == 34 ) { if ( sum < limit ) sum = sum + val; if ( val >= limit ) val = sum - limit; else val = 0; } else if ( val = -12 ) sum = 0; else limit = 88;

A mail order company charges $3.00 for handling, free shipping for orders 10 pounds or less, plus $0.25 for each pound over 10. Write a program that repeatedly asks the user for the weight of an order, then writes out the shipping charge. The program stops when a weight of zero or less is entered. Weight of Order: 5 Shipping Cost: $3.00 Weight of Order 20 Shipping Cost: $5.50 Weight of Order 0 bye

You might also like