Sentinel Loops

download Sentinel Loops

of 22

Transcript of Sentinel Loops

  • 8/13/2019 Sentinel Loops

    1/22

    Sentinel Controlled Loops

    Say that a program is to add up a list ofnumbers entered from the keyboard. Will aloop be used in this program?

    Answer..yes: A counting loop could dothis if the user first said how many integerswere in the list. But often users don't know

    this in advance so, what do we do?

  • 8/13/2019 Sentinel Loops

    2/22

    The idea of a sentinel controlled loopis thatthere is a special value (the sentinel) that is usedto say when the loop is done. In this example,

    the user enters a zero when the sum iscomplete. Zero is the sentinel. Here is how theprogram should work:

    C:\Enter first integer (enter 0 to quit): 1Enter 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

  • 8/13/2019 Sentinel Loops

    3/22

    The flow chart

  • 8/13/2019 Sentinel Loops

    4/22

    Partially completed programimport 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 );} }

  • 8/13/2019 Sentinel Loops

    5/22

    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?

  • 8/13/2019 Sentinel Loops

    6/22

    What if we wanted to modify the program so that it promptsthe 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 21thinteger (enter 0 to quit): The prompt shows poorgrammar for integers 21, 22, 23, 31, 32, 33 and so on.Let us regard this as acceptable.

  • 8/13/2019 Sentinel Loops

    7/22

    Just to remind you.

  • 8/13/2019 Sentinel Loops

    8/22

    So .what do we need to do

    Change the output line

    System.out.println( "Enter the " + (count+1)+ suffix+ " integer (enter 0 to quit):" );

  • 8/13/2019 Sentinel Loops

    9/22

    We have three choices

    To make a three-way choice, a nested if isused. This is where an if-else statement ispart of a the true-branch (or false-branch)

    of another if-else statement. So the nestedif-else will execute only when the outer if-else has already made a choice between

    two branches. Here is a program fragmentthat makes a choice of one of the threesuffixes.

  • 8/13/2019 Sentinel Loops

    10/22

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

  • 8/13/2019 Sentinel Loops

    11/22

    Matching if's and else's

    Start with the first ifand work downward.Each elsematches the closest previous

    unmatched if. An if matches only one elseand an elsematches only one if.

  • 8/13/2019 Sentinel Loops

    12/22

    Here is another example. It is not indentedproperly. Use the rule to figure out which

    ifs and ifs match.

    if ( a == b )

    if ( d == e )

    total = 0;

    else

    total = total + a;

    else

    total = total + b;

  • 8/13/2019 Sentinel Loops

    13/22

    Make Matches clear with Braces

    In this case, the braces are not reallyneeded, but are probably a good idea, forclarity:

    if ( a == b )

    {

    if ( d == e )

    total = 0;

    else

    total = total + b;

    }

  • 8/13/2019 Sentinel Loops

    14/22

    New Example

    Sometimes the user is asked explicitly if theloop should continue. The user enters

    "yes" or "no" (or maybe "y" or "n"). Nowthe sentinelis of type String or char. Thenext example illustrates this: Say that you

    are interested in the value of thepolynomial:

  • 8/13/2019 Sentinel Loops

    15/22

    7x3- 3x2+ 4x - 12

    or various values of x. The value x is adouble 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 forx and see the result for each one.

  • 8/13/2019 Sentinel Loops

    16/22

    Testing the User's Responseclass 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".

    } } }

  • 8/13/2019 Sentinel Loops

    17/22

    The condition part of the while statement,response.equals("y") evaluates to trueor false. Here ishow 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 isequal to it.

    response.equals("y") tests if the String response is equal to theString "y".

    The result of the test is trueor false.

  • 8/13/2019 Sentinel Loops

    18/22

    So, what all do I need

    As with all loops, there were three thingsto get right:

    Initializing the loop. Testing if the loop should continue.

    Setting up for the next test.

  • 8/13/2019 Sentinel Loops

    19/22

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

    }

    }}

  • 8/13/2019 Sentinel Loops

    20/22

    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;

    }

  • 8/13/2019 Sentinel Loops

    21/22

    IF ( val == 34 )

    {

    if ( sum < limit )

    sum = sum + val;

    if ( val >= limit )

    val = sum - limit;

    else

    val = 0;

    }

    elseif ( val = -12 )

    sum = 0;

    else

    limit = 88;

  • 8/13/2019 Sentinel Loops

    22/22

    A mail order company charges $3.00 for handling, freeshipping for orders 10 pounds or less, plus $0.25 foreach pound over 10. Write a program that repeatedly

    asks the user for the weight of an order, then writes outthe shipping charge. The program stops when a weightof zero or less is entered.

    Weight of Order: 5Shipping Cost: $3.00

    Weight of Order 20

    Shipping Cost: $5.50

    Weight of Order 0

    bye