125
1 Iteration Chapter 4 Spring 2007 CS 101 Aaron Bloomfield

06 Ch4 Iteration

Embed Size (px)

DESCRIPTION

,,,,,,

Citation preview

  • 1Iteration

    Chapter 4Spring 2007CS 101Aaron Bloomfield

  • 2Java looping Options while do-while for

    Allow programs to control how many times a statement list is executed

  • 33

    Averaging valuesAveraging values

  • 4Averaging Problem Extract a list of positive numbers from standard input and

    produce their average Numbers are one per line A negative number acts as a sentinel to indicate that

    there are no more numbers to process

    Observations Cannot supply sufficient code using just assignments and

    conditional constructs to solve the problem Dont how big of a list to process

    Need ability to repeat code as needed

  • 5Averaging Algorithm Prepare for processing Get first input While there is an input to process do { Process current input Get the next input

    } Perform final processing

  • 6Averaging Problem Extract a list of positive numbers from standard input and

    produce their average Numbers are one per line A negative number acts as a sentinel to indicate that

    there are no more numbers to process

    Sample runEnter positive numbers one per line.

    Indicate end of list with a negative number.

    4.5

    0.5

    1.3

    -1

    Average 2.1

  • public class NumberAverage {// main(): application entry pointpublic static void main(String[] args) {

    // set up the input

    // prompt user for values

    // get first value

    // process values one-by-onewhile (value >= 0) {

    // add value to running total// processed another value// prepare next iteration - get next value

    }

    // display resultif (valuesProcessed > 0)

    // compute and display averageelse

    // indicate no average to display}

    }

  • int valuesProcessed = 0;

    double valueSum = 0;

    // set up the input

    Scanner stdin = new Scanner (System.in);

    // prompt user for values

    System.out.println("Enter positive numbers 1 per line.\n"

    + "Indicate end of the list with a negative number.");

    // get first value

    double value = stdin.nextDouble();

    // process values one-by-one

    while (value >= 0) {

    valueSum += value;

    ++valuesProcessed;

    value = stdin.nextDouble();

    }

    // display result

    if (valuesProcessed > 0) {

    double average = valueSum / valuesProcessed;

    System.out.println("Average: " + average);

    } else {

    System.out.println("No list to average");

    }

  • 99

    Program DemoProgram Demo

    NumberAverage.javaNumberAverage.java

  • 10

    While syntax and semantics

    Logical expression thatdetermines whether Action

    is to be executed

    while ( Expression ) Action

    Action is either a singlestatement or a statement

    list within braces

  • 11

    While semantics for averaging problem

    // process values one-by-onewhile ( value >= 0 ) {

    // add value to running totalvalueSum += value;

    // we processed another value++valueProcessed;

    // prepare to iterate get the next inputvalue = stdin.nextDouble();

    }

    Test expression is evaluated at thestart of each iteration of the loop.

    If test expression is true, these statementsare executed. Afterward, the test expression

    is reevaluated and the process repeats

  • 12

    While Semantics

    Expression

    Action

    true false

    Expression isevaluated at the

    start of eachiteration of the

    loop

    If Expression istrue, Action is

    executed If Expression isfalse, program

    executioncontinues with

    next statement

  • 13

    int valuesProcessed = 0;double valueSum = 0;

    double value = stdin.nextDouble();

    while (value >= 0) {valueSum += value;++valuesProcessed;value = stdin.nextDouble();

    }

    if (valuesProcessed > 0) {double average = valueSum / valuesProcessed;System.out.println("Average: " + average);

    }else {

    System.out.println("No list to average");}

    int valuesProcessed = 0;double valueSum = 0;

    double value = stdin.nextDouble();

    while (value >= 0) {valueSum += value;++valuesProcessed;value = stdin.nextDouble();

    if (valuesProcessed > 0) {double average = valueSum / valuesProcessed;System.out.println("Average: " + average);

    Suppose input contains: 4.5 0.5 1.3 -1

    Execution Trace 0valueSum

    valuesProcessed0

    value 4.5

    Suppose input contains: 4.5 0.5 1.3 -1

    4.5

    1

    Suppose input contains: 4.5 0.5 1.3 -1

    0.5

    5.0

    2

    1.3

    6.3

    Suppose input contains: 4.5 0.5 1.3 -1

    3

    -1

    Suppose input contains: 4.5 0.5 1.3 -1

    average 2.1

  • 1414

    What do these pictures mean?What do these pictures mean?

    Light beerLight beer Dandy lionsDandy lions Assaulted Assaulted

    peanutpeanut EggplantEggplant Dr. PepperDr. Pepper Pool tablePool table Tap dancersTap dancers Card sharkCard shark King of popKing of pop I PodI Pod Gator aideGator aide Knight mareKnight mare Hole milkHole milk

  • 1515

    Converting text to lower caseConverting text to lower case

  • 16

    Converting text to strictly lowercasepublic static void main(String[] args) {

    Scanner stdin = new Scanner (System.in);

    System.out.println("Enter input to be converted:");

    String converted = "";

    while (stdin.hasNext()) {String currentLine = stdin.nextLine();String currentConversion =

    currentLine.toLowerCase();converted += (currentConversion + "\n");

    }

    System.out.println("\nConversion is:\n" + converted);

    }

  • 17

    Sample run

    A Ctrl+z wasentered. It is theWindows escape

    sequence forindicatingend-of-file

    An empty linewas entered

  • 1818

    Program DemoProgram Demo

    LowerCaseDisplay.javaLowerCaseDisplay.java

  • 19

    Program tracepublic static void main(String[] args) {

    Scanner stdin = new Scanner (System.in);

    System.out.println("Enter input to be converted:");

    String converted = "";

    while (stdin.hasNext()) {

    String currentLine = stdin.nextLine();

    String currentConversion =

    currentLine.toLowerCase();

    converted += (currentConversion + "\n");

    }

    System.out.println("\nConversion is:\n" +

    converted);

    }

    public static void main(String[] args) {

    Scanner stdin = new Scanner (System.in);

    System.out.println("Enter input to be converted:");

    String converted = "";

    while (stdin.hasNext()) {

    String currentLine = stdin.nextLine();

    String currentConversion =

    currentLine.toLowerCase();

    converted += (currentConversion + "\n");

    }

    System.out.println("\nConversion is:\n" +

    converted);

    }

  • 20

    Program trace

    Representation of lower caseconversion of current input line

    converted += (currentConversion + "\n");

    The append assignment operator updates the representationof converted to include the current input line

    Newline character is neededbecause method nextLine()

    "strips" them from the input

  • 2121

    Another optical illusionAnother optical illusion

  • 2222

    Loop Design & Reading From Loop Design & Reading From a Filea File

  • 23

    Loop design Questions to consider in loop design and analysis What initialization is necessary for the loops test

    expression?

    What initialization is necessary for the loops processing? What causes the loop to terminate? What actions should the loop perform? What actions are necessary to prepare for the next

    iteration of the loop?

    What conditions are true and what conditions are false when the loop is terminated?

    When the loop completes what actions are need to prepare for subsequent program processing?

  • 24

    Reading a file Background

    Same Scanner class!

    Scanner fileIn = new Scanner (new File (filename) );

    The File class allows access to filesIts in the java.io package

    filename is a String

  • 25

    Reading a file Class File Allows access to files (etc.) on a hard drive

    Constructor File (String s) Opens the file with name s so that values can be

    extracted Name can be either an absolute pathname or a pathname

    relative to the current working folder

  • 26

    Reading a fileScanner stdin = new Scanner (System.in);

    System.out.print("Filename: ");

    String filename = stdin.nextLine();

    Scanner fileIn = new Scanner (new File (filename));

    String currentLine = fileIn.nextLine();

    while (currentLine != null) {

    System.out.println(currentLine);

    currentLine = fileIn.nextLine();

    }

    Scanner stdin = new Scanner (System.in);

    System.out.print("Filename: ");

    String filename = stdin.nextLine();

    Scanner fileIn = new Scanner (new File (filename));

    String currentLine = fileIn.nextLine();

    while (currentLine != null) {

    System.out.println(currentLine);

    currentLine = fileIn.nextLine();

    }Set up standard input streamDetermine file nameSet up file streamProcess lines one by oneGet first lineMake sure got a line to processDisplay current lineGet next lineMake sure got a line to processIf not, loop is doneClose the file stream

  • 2727

    TodayTodays s demotivatorsdemotivators

  • 2828

    The For statementThe For statement

  • 29

    The For Statement

    currentTerm = 1;

    for ( int i = 0; i < 5; ++i ) {System.out.println(currentTerm);currentTerm *= 2;

    }

    After each iteration of thebody of the loop, the updateexpression is reevaluated

    The body of the loop iterateswhile the test expression istrue

    int

    Initialization stepis performed onlyonce -- just prior

    to the firstevaluation of thetest expression

    The body of the loop displays thecurrent term in the number series.It then determines what is to be thenew current number in the series

  • ForExpr

    Action

    true false

    ForInit

    ForUpdate

    Evaluated onceat the beginning

    of the forstatements's

    executionThe ForExpr is

    evaluated at thestart of each

    iteration of theloop

    If ForExpr is true,Action isexecuted

    After the Actionhas completed,

    thePostExpression

    is evaluated

    If ForExpr isfalse, program

    executioncontinues with

    next statement

    After evaluating thePostExpression, the next

    iteration of the loop starts

  • 31

    for statement syntax

    Logical test expression that determines whether the action and update step areexecuted

    for ( ForInit ; ForExpression ; ForUpdate ) Action

    Update step is performed afterthe execution of the loop body

    Initialization step prepares for thefirst evaluation of the test

    expression

    The body of the loop iterates wheneverthe test expression evaluates to true

  • 32

    for vs. while A for statement is almost like a while statement

    for ( ForInit; ForExpression; ForUpdate ) Action

    is ALMOST the same as:

    ForInit;

    while ( ForExpression ) {

    Action;

    ForUpdate;

    }

    This is not an absolute equivalence! Well see when they are different in a bit

  • 33

    Variable declaration You can declare a variable in any block:

    while ( true ) {

    int n = 0;

    n++;

    System.out.println (n);

    }

    System.out.println (n);

    Variable n gets created (and initialized) each time

    Thus, println() always prints out 1

    Variable n is not defined once while

    loop ends

    As n is not defined here, this causes

    an error

  • 34

    Variable declaration You can declare a variable in any block:

    if ( true ) {

    int n = 0;

    n++;

    System.out.println (n);

    }

    System.out.println (n);

    Only difference from last slide

  • 35

    System.out.println("i is " + i);

    }

    System.out.println("all done");

    System.out.println("i is " + i);

    }

    System.out.println("all done");

    i is 0

    i is 1

    i is 2

    all done

    iExecution Trace

    0int i = 0; i < 3; ++ifor ( ) {int i = 0; i < 3; ++i 123

    Variable i has gone out of scope it

    is local to the loop

  • 36

    for vs. while An example when a for loop can be directly translated into a while

    loop:

    int count;

    for ( count = 0; count < 10; count++ ) {

    System.out.println (count);

    }

    Translates to:

    int count;

    count = 0;

    while (count < 10) {

    System.out.println (count);

    count++;

    }

  • 37

    for vs. while An example when a for loop CANNOT be directly translated

    into a while loop:

    for ( int count = 0; count < 10; count++ ) {

    System.out.println (count);

    }

    Would (mostly) translate as:

    int count = 0;

    while (count < 10) {

    System.out.println (count);

    count++;

    }count IS defined here

    count is NOT defined here

    only difference

  • 38

    for loop indexing Java (and C and C++) indexes everything from zero

    Thus, a for loop like this:

    for ( int i = 0; i < 10; i++ ) { ... }

    Will perform the action with i being value 0 through 9, but not 10

    To do a for loop from 1 to 10, it would look like this:

    for ( int i = 1; i

  • 39

    Nested loopsint m = 2;

    int n = 3;

    for (int i = 0; i < n; ++i) {

    System.out.println("i is " + i);

    for (int j = 0; j < m; ++j) {

    System.out.println(" j is " + j);

    }

    }i is 0

    j is 0

    j is 1

    i is 1

    j is 0

    j is 1

    i is 2

    j is 0

    j is 1

  • 40

    Nested loopsint m = 2;

    int n = 4;

    for (int i = 0; i < n; ++i) {

    System.out.println("i is " + i);

    for (int j = 0; j < i; ++j) {

    System.out.println(" j is " + j);

    }

    }

    i is 0

    i is 1

    j is 0

    i is 2

    j is 0

    j is 1

    i is 3

    j is 0

    j is 1

    j is 2

  • 41

    How well do you understand for loops?How well do you understand for loops?

    Very

    well!

    This

    stuff i

    ...

    Fairly

    well

    wi

    th a l

    itt..

    Oka

    y. It

    s not

    grea

    t, bu..

    .

    Not

    well.

    Im ki

    nda c

    ...

    Not

    at all

    . Im

    sooo

    oo...

    20% 20% 20%20%20%1.1. Very well! This stuff Very well! This stuff is easy!is easy!2.2. Fairly well Fairly well with a with a

    little review, Ilittle review, Ill be ll be goodgood

    3.3. Okay. ItOkay. Its not great, s not great, but itbut its not horrible, s not horrible, eithereither

    4.4. Not well. INot well. Im m kindakindaconfusedconfused

    5.5. Not at all. INot at all. Im m soooooosoooooo lostlost

  • 4242

    From DubaiFrom Dubai

  • 4343

    dodo--while loopswhile loops

  • 44

    The do-while statement Syntax

    do Actionwhile (Expression)

    Semantics Execute Action If Expression is true then

    execute Action again Repeat this process until

    Expression evaluates to false

    Action is either a single statement or a group of statements within braces

    Action

    true

    false

    Expression

  • 45

    Picking off digits Consider

    System.out.print("Enter a positive number: ");

    int number = stdin.nextInt();

    do {

    int digit = number % 10;

    System.out.println(digit);

    number = number / 10;

    } while (number != 0);

    Sample behaviorEnter a positive number: 1129

    9

    2

    1

    1

  • 46

    Guessing a number This program will allow the user to guess the number the

    computer has thought of

    Main code block:

    do {

    System.out.print ("Enter your guess: ");

    guessedNumber = stdin.nextInt();

    count++;

    } while ( guessedNumber != theNumber );

  • 4747

    Program DemoProgram Demo

    GuessMyNumber.javaGuessMyNumber.java

  • 48

    while vs. do-while If the condition is false: while will not execute the action do-while will execute it once

    while ( false ) {

    System.out.println (foo);

    }

    do {

    System.out.println (foo);

    } while ( false );

    never executed

    executed once

  • 49

    while vs. do-while A do-while statement can be translated into a while

    statement as follows:

    do {

    Action;

    } while ( WhileExpression );

    can be translated into:

    boolean flag = true;

    while ( WhileExpression || flag ) {

    flag = false;

    Action;

    }

  • 50

    How well do you understand doHow well do you understand do--while loops?while loops?

    Very

    well!

    This

    stuff i

    ...

    Fairly

    well

    wi

    th a l

    itt..

    Oka

    y. It

    s not

    grea

    t, bu..

    .

    Not

    well.

    Im ki

    nda c

    ...

    Not

    at all

    . Im

    sooo

    oo...

    20% 20% 20%20%20%1.1. Very well! This stuff Very well! This stuff is easy!is easy!2.2. Fairly well Fairly well with a with a

    little review, Ilittle review, Ill be ll be goodgood

    3.3. Okay. ItOkay. Its not great, s not great, but itbut its not horrible, s not horrible, eithereither

    4.4. Not well. INot well. Im m kindakindaconfusedconfused

    5.5. Not at all. INot at all. Im m soooooosoooooo lostlost

  • 5151

    TodayTodays s demotivatorsdemotivators

  • 5252

    Loop controlsLoop controls

  • 53

    The continue keyword The continue keyword will immediately start the next iteration of the

    loop The rest of the current loop is not executed But the ForUpdate part is, if continue is in a for loop

    for ( int a = 0; a

  • 54

    The break keyword The break keyword will immediately stop the execution of the loop

    Execution resumes after the end of the loop

    for ( int a = 0; a

  • 5555

    Four HobosFour Hobos

  • 56

    Four Hobos An example of a program that uses nested for loops

    Credited to Will Shortz, crossword puzzle editor of the New York Times And NPRs Sunday Morning Edition puzzle person

  • 57

    Problem Four hobos want to split up 200 hours of work The smart hobo suggests that they draw straws with numbers

    on it If a straw has the number 3, then they work for 3 hours on 3

    days (a total of 9 hours) The smart hobo manages to draw the shortest straw How many ways are there to split up such work? Which one did the smart hobo choose?

  • 58

    Analysis We are looking for integer solutions to the formula:

    a2+b2+c2+d2 = 200 Where a is the number of hours & days the first hobo

    worked, b for the second hobo, etc.

    We know the following: Each number must be at least 1 No number can be greater than 200 = 14 That order doesnt matter The combination (1,2,1,2) is the same as (2,1,2,1) Both combinations have two short and two long

    straws

    We will implement this with nested for loops

  • 59

    Implementationpublic class FourHobos {

    public static void main (String[] args) {for ( int a = 1; a

  • 6060

    Program DemoProgram Demo

    FourHobos.javaFourHobos.java

  • 61

    Results The output:

    (2, 4, 6, 12)

    (6, 6, 8, 8)

    Not surprisingly, the smart hobo picks the short straw of the first combination

  • 6262

    TodayTodays s demotivatorsdemotivators

  • 63

    Alternate implementation We are going to rewrite the old code in the inner most for

    loop:

    if ( (a

  • 64

    Alternate implementation This is the new code for the inner-most for loop:

    if ( (a > b) || (b > c) || (c > d) ) {

    continue;

    }

    if ( a*a+b*b+c*c+d*d != 200 ) {

    continue;

    }

    System.out.println ("(" + a + ", " + b + ", "

    + c + ", " + d + ")");

  • 65

    How well do you understand four hobos?How well do you understand four hobos?

    Very

    well!

    This

    stuff i

    ...

    Fairly

    well

    wi

    th a l

    itt..

    Oka

    y. It

    s not

    grea

    t, bu..

    .

    Not

    well.

    Im ki

    nda c

    ...

    Not

    at all

    . Im

    sooo

    oo...

    20% 20% 20%20%20%1.1. Very well! This stuff Very well! This stuff is easy!is easy!2.2. Fairly well Fairly well with a with a

    little review, Ilittle review, Ill be ll be goodgood

    3.3. Okay. ItOkay. Its not great, s not great, but itbut its not horrible, s not horrible, eithereither

    4.4. Not well. INot well. Im m kindakindaconfusedconfused

    5.5. Not at all. INot at all. Im m soooooosoooooo lostlost

  • 6666

    OrnithologyOrnithology NutritionNutrition PeacePeace

    AcousticsAcoustics

    MathematicsMathematics

    LiteratureLiterature

    MedicineMedicine

    PhysicsPhysics ChemistryChemistry

    BiologyBiology

    The 2006 The 2006 IgIg Nobel PrizesNobel PrizesFor explaining why woodpeckers donFor explaining why woodpeckers dont get headachest get headachesFor showing that Kuwaiti dung beetles are finicky eatersFor showing that Kuwaiti dung beetles are finicky eatersFor development of a highFor development of a high--pitched electronic teenpitched electronic teen--ager ager

    repellent (and, later, ring tones)repellent (and, later, ring tones)For experiments to determine why people donFor experiments to determine why people dont like the sound t like the sound

    of fingernails scraping on a blackboardof fingernails scraping on a blackboardFor calculating the number of photos you must take to ensure For calculating the number of photos you must take to ensure

    that (almost) nobody in a group will have their eyes closedthat (almost) nobody in a group will have their eyes closedFor a report entitled, For a report entitled, Consequences of Erudite Vernacular Consequences of Erudite Vernacular

    Utilized Irrespective of Necessity: Problems with Using Utilized Irrespective of Necessity: Problems with Using Long Words Needlessly.Long Words Needlessly.

    For a medical case report titled, For a medical case report titled, "Termination of Intractable "Termination of Intractable Hiccups with Digital Rectal MassageHiccups with Digital Rectal Massage

    For studying why dry spaghetti breaks into multiple piecesFor studying why dry spaghetti breaks into multiple piecesFor a study entitled, For a study entitled, Ultrasonic Velocity in Cheddar Cheese as Ultrasonic Velocity in Cheddar Cheese as

    Affected by Temperature," Affected by Temperature," For showing that the female malaria mosquito is equally For showing that the female malaria mosquito is equally

    attracted to the smells of limburger cheese and human feetattracted to the smells of limburger cheese and human feet

  • 6767

    3 card poker3 card poker

  • 68

    3 Card Poker This is the looping HW from a previous fall The problem: count how many of each type of hand in a 3

    card poker game

    Standard deck of 52 cards (no jokers) Four suits: spades, clubs, diamonds, hearts 13 Faces: Ace, 2 through 10, Jack, Queen, King

    Possible 3-card poker hands Pair: two of the cards have the same face value Flush: all the cards have the same suit Straight: the face values of the cards are in succession Three of a kind: all three cards have the same face value Straight flush: both a flush and a straight

  • 69

    The Card class A Card class was provided Represents a single card in the deck

    Constructor: Card(int i) If i is in the inclusive interval 1 ... 52 then a card is

    configured in the following manner If 1

  • 70

    Card class methods String getFace() Returns the face of the card as a String

    String getSuit() Returns the suit of the card as a String

    int getValue() Returns the value of the card

    boolean equals(Object c) Returns whether c is a card that has the same face and

    suit as the invoking card String toString() Returns a text representation of the card. You may find

    this method useful during debugging.

  • 71

    The Hand class A Hand class was (partially) provided Represents the three cards the player is holding

    Constuctor: Hand(Card c1, Card c2, Card c3) Takes those cards and puts them in sorted order

  • 72

    Provided Hand methods public Card getLow() Gets the low card in the hand

    public Card getMiddle() Gets the middle card in the hand

    public Card getHigh() Gets the high card in the hand

    public String toString() Well see the use of the toString() method later

    public boolean isValid() Returns if the hand is a valid hand (no two cards that are

    the same) public boolean isNothing() Returns if the hand is not one of the winning hands

    described before

  • 73

    Hand Methods to Implement The assignment required the students to implement the other

    methods of the Hand class We havent seen this yet

    The methods returned true if the Hand contained a winningcombination of cards public boolean isPair() public boolean isThree() public boolean isStraight() public boolean isFlush() public boolean isStraightFlush()

  • 74

    Class HandEvaluation Required nested for loops to count the total number of each

    hand

    Note that the code for this part may not appear on the website

  • 7575

    Program DemoProgram Demo

    HandEvaluation.javaHandEvaluation.java

  • 76

    How well do you understand 3How well do you understand 3--card poker?card poker?

    Very

    well!

    This

    stuff i

    ...

    Fairly

    well

    wi

    th a l

    itt..

    Oka

    y. It

    s not

    grea

    t, bu..

    .

    Not

    well.

    Im ki

    nda c

    ...

    Not

    at all

    . Im

    sooo

    oo...

    20% 20% 20%20%20%1.1. Very well! This stuff Very well! This stuff is easy!is easy!2.2. Fairly well Fairly well with a with a

    little review, Ilittle review, Ill be ll be goodgood

    3.3. Okay. ItOkay. Its not great, s not great, but itbut its not horrible, s not horrible, eithereither

    4.4. Not well. INot well. Im m kindakindaconfusedconfused

    5.5. Not at all. INot at all. Im m soooooosoooooo lostlost

  • 7777

    All your base are belong to usAll your base are belong to us

    Flash animationFlash animation Reference: http://Reference: http://en.wikipedia.org/wiki/All_your_base_are_belong_to_usen.wikipedia.org/wiki/All_your_base_are_belong_to_us

  • 7878

    The Halting ProblemThe Halting Problem

  • 79

    Whats wrong with this program?

    public class LoopsForever {public static void main (String args[]) {

    while ( true ) {System.out.println ();

    }}

    }

    Given a more complicated program, how do we tell if it gets stuck in an infinite loop? Such as when an application hangs?

  • 80

  • 81

    The Halting problem Given a Java program P, and input I Let P be a filename for a program file on a disk

    somewhere Let I be a filename for a file that contains all the input the

    program takes in

    Will the program P with input I ever terminate? Meaning will program P with input I loop forever or halt?

    Can a computer program determine this? Can a human?

    First shown by Alan Turing in 1936 Before digital computers existed! (Im ignoring which way he showed it for now)

  • 82

    A few notes To solve the halting problem means we have a method

    Oracle.CheckHalt (String P, String I) Let Oracle be a class that can give lots of (truthful)

    answers Oracle.PredictFuture(),

    Oracle.GetNextLotteryNumbers(), etc. P is the (filename of the) program we are checking for

    halting I is the (filename of the) input to that program

    And it will return loops forever or halts As a boolean: true means loops forever, false means

    halts Note it must work for any (Java) program, not just some

    programs Or simple programs

  • 83

    Take your best guess Take your best guess do you think itdo you think its s possible to solve the halting problem?possible to solve the halting problem?

    Yes

    No

    I don

    t und

    erstan

    d wh..

    33% 33%33%1.1. YesYes2.2. NoNo3.3. I donI dont understand t understand

    what the halting what the halting problem isproblem is

  • 84

    Can a human determine if a program halts?

    Given a program of 10 lines or less, can a human determine if it halts? Assuming no tricks the program is completely

    understandable And assuming the computer works properly, of course

    And we ignore the fact that an int will max out at 4 billion As there are ways we can get around this

    For the sample programs on the next page: Assume that the code is in a proper main() method in a

    proper class Assume print stands for System.out.print Likewise for println

  • 85

    Halting problem examples: will they halt? First sample program:

    ...println (Alan Turing);

    ...println (was a genius);System.exit();

    Second sample program:

    for (int n = 0; n < 10; n++)...println (n);

    System.exit();

    Third sample program

    while (true)...println (hello world);

    System.exit();

    Fourth sample program:

    int x = 10;while ( x > 0 ) {

    ...println (hello world);x = x + 1;

    }System.exit();

  • 86

    Take your best guess Take your best guess do you think itdo you think its s possible to solve the halting problem?possible to solve the halting problem?

    Yes

    No

    I don

    t und

    erstan

    d wh..

    33% 33%33%1.1. YesYes2.2. NoNo3.3. I donI dont understand t understand

    what the halting what the halting problem isproblem is

  • 87

    Perfect numbers Numbers whose divisors (not including the number) add

    up to the number 6 = 1 + 2 + 3 28 = 1 + 2 + 4 + 7 + 14

    The list of the first 10 perfect numbers:6, 28, 496, 8128, 33550336, 8589869056, 137438691328, 2305843008139952128, 2658455991569831744654692615953842176, 191561942608236107294793378084303638130997321548169216 The last one was 54 digits!

    All known perfect numbers are even; its an open (i.e. unsolved) problem if odd perfect numbers exist

    Sequence A000396 in OEIS

  • 88

    Odd perfect number search Will this program ever halt?

    int n = 1; // arbitrary-precision integerwhile (true) {

    int sumOfFactors = 0;for ( int factor = 1; factor < n; factor++ )

    if ( n % factor == 0 ) // factor is a factor of nsumOfFactors = sumOfFactors + factor;

    if (sumOfFactors == n) thenbreak;

    n = n + 2;}System.out.exit();

    Adapted from http://en.wikipedia.org/wiki/Halting_problem

  • 89

    Take your best guess Take your best guess do you think itdo you think its s possible to solve the halting problem?possible to solve the halting problem?

    Yes

    No

    I don

    t und

    erstan

    d wh..

    33% 33%33%1.1. YesYes2.2. NoNo3.3. I donI dont understand t understand

    what the halting what the halting problem isproblem is

  • 90

    Where does that leave us?

    If a human cant figure out how to do the halting problem, we cant make a computer do it for us

    It turns out that it is impossible to write such a CheckHalt() method But how to prove this?

  • 91

    CheckHalt()s non-existence Consider a program P with input I Suppose that a method Oracle.CheckHalt(P,I) exists Tests if P(I) will either loop forever or halt

    A program is a series of bits And thus can be considered data as well

    Thus, we can call CheckHalt(P,P) Its using the bytes of program P as the input to

    program P

  • 92

    CheckHalt()s non-existence Consider a new program:

    public class Test {public static void main (String args[]) {

    if ( Oracle.CheckHalt(Test.java, Test.java) )// if Test.java loops forever

    System.exit(); // then haltelse // else if Test.java halts

    while (true) { } // then loop forever}

    }

    Do we agree that class Test is a valid program?

  • 93

    CheckHalt()s non-existence A (somewhat condensed)

    version of class Test:

    public class Test { main (String args[]) {

    if ( Oracle.CheckHalt(Test.java, Test.java) )

    System.exit(); else

    while (true) { } }

    }

    Two possibilities:

    Either class Test halts Then CheckHalt(Test,Test)

    returns true (loops forever)

    Which means that class Test loops forever

    Contradiction!

    Or class Test loops forever Then CheckHalt(Test,Test)

    returns false (halts) Which means that class

    Test halts Contradiction!

  • 94

    How well do you understand How well do you understand the halting problem?the halting problem?

    Very

    well!

    This

    stuff i

    ...

    Fairly

    well

    wi

    th a l

    itt..

    Oka

    y. It

    s not

    grea

    t, bu..

    .

    Not

    well.

    Im ki

    nda c

    ...

    Not

    at all

    . Im

    sooo

    oo...

    20% 20% 20%20%20%1.1. Very well! This stuff Very well! This stuff is easy!is easy!2.2. Fairly well Fairly well with a with a

    little review, Ilittle review, Ill be ll be goodgood

    3.3. Okay. ItOkay. Its not great, s not great, but itbut its not horrible, s not horrible, eithereither

    4.4. Not well. INot well. Im m kindakindaconfusedconfused

    5.5. Not at all. INot at all. Im m soooooosoooooo lostlost

  • 95

    Why do we care about the halting problem?

    It was the first algorithm that was shown to not be able to exist by a computer You can prove something exists by showing an example

    (a correct program) But its much harder to prove that a program can never

    exist

    First shown by Alan Turing in 1936 Before digital computers existed!

  • 9696

    New 2005 New 2005 demotivatiorsdemotivatiors!!

  • 9797

    Not going over any more Not going over any more slides in this slide setslides in this slide set

  • 9898

    Triangle countingTriangle counting

  • 99

    The programming assignment This was the looping HW from two springs ago

    List all the possible triangles from (1,1,1) to (n,n,n) Where n is an inputted number In particular, list their triangle type

    Types are: equilateral, isosceles, right, and scalene

  • 100

    Sample executionEnter n: 5

    (1,1,1) isosceles equilateral(1,2,2) isosceles(1,3,3) isosceles(1,4,4) isosceles(1,5,5) isosceles(2,2,2) isosceles equilateral(2,2,3) isosceles(2,3,3) isosceles(2,3,4) scalene(2,4,4) isosceles(2,4,5) scalene

    (2,5,5) isosceles(3,3,3) isosceles equilateral(3,3,4) isosceles(3,3,5) isosceles(3,4,4) isosceles(3,4,5) right scalene(3,5,5) isosceles(4,4,4) isosceles equilateral(4,4,5) isosceles(4,5,5) isosceles(5,5,5) isosceles equilateral

  • 101101

    Program DemoProgram Demo

    TriangleDemo.javaTriangleDemo.java

  • 102

    The Triangle class That semester we went over classes by this homework So they had to finish the class We will be seeing class creation after spring break

    Methods in the class: public Triangle() public Triangle (int x, int y, int z) public boolean isTriangle() public boolean isRight() public boolean isIsosceles() public boolean isScalene() public boolean isEquilateral() public String toString()

  • 103

    The TriangleDemo class Contained a main() method that tested all the triangles

    Steps required: Check if the sides are in sorted order (i.e. x < y < z) If not, then no output should be provided for that collection

    of side lengths Create a new Triangle object using the current side lengths Check if it is a valid triangle If it is not, then no output should be provided for that

    collection of side lengths Otherwise, indicate which properties the triangle possesses Some side length values will correspond to more than 1

    triangle e.g., (3, 3, 3) is both isosceles and equilateral Thus, we cant assume that once a property is present, the

    others are not.

  • 104104

    Look at that them there codeLook at that them there code

    TriangleDemo.javaTriangleDemo.java

  • 105

    How well do you understand triangle counting?How well do you understand triangle counting?

    Very

    well!

    This

    stuff i

    ...

    Fairly

    well

    wi

    th a l

    itt..

    Oka

    y. It

    s not

    grea

    t, bu..

    .

    Not

    well.

    Im ki

    nda c

    ...

    Not

    at all

    . Im

    sooo

    oo...

    20% 20% 20%20%20%1.1. Very well! This stuff Very well! This stuff is easy!is easy!2.2. Fairly well Fairly well with a with a

    little review, Ilittle review, Ill be ll be goodgood

    3.3. Okay. ItOkay. Its not great, s not great, but itbut its not horrible, s not horrible, eithereither

    4.4. Not well. INot well. Im m kindakindaconfusedconfused

    5.5. Not at all. INot at all. Im m soooooosoooooo lostlost

  • 106106

    Fibonacci numbersFibonacci numbers

  • 107

    Fibonacci sequence Sequences can be neither geometric or arithmetic Fn = Fn-1 + Fn-2, where the first two terms are 1 Alternative, F(n) = F(n-1) + F(n-2)

    Each term is the sum of the previous two terms Sequence: { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, } This is the Fibonacci sequence

    Full formula:

    ( ) ( )n

    nn

    nF25

    5151)( +=

  • 108

    Fibonacci sequence in nature

    1385321

  • 109

    Reproducing rabbits You have one pair of rabbits on an island The rabbits repeat the following: Get pregnant one month Give birth (to another pair) the next month

    This process repeats indefinitely (no deaths) Rabbits get pregnant the month they are born

    How many rabbits are there after 10 months?

  • 110

    Reproducing rabbits First month: 1 pair The original pair

    Second month: 1 pair The original (and now pregnant) pair

    Third month: 2 pairs The child pair (which is pregnant) and the parent pair

    (recovering) Fourth month: 3 pairs Grandchildren: Children from the baby pair (now

    pregnant) Child pair (recovering) Parent pair (pregnant)

    Fifth month: 5 pairs Both the grandchildren and the parents reproduced 3 pairs are pregnant (child and the two new born rabbits)

  • 111

    Reproducing rabbits Sixth month: 8 pairs All 3 new rabbit pairs are pregnant, as well as those not

    pregnant in the last month (2) Seventh month: 13 pairs All 5 new rabbit pairs are pregnant, as well as those not

    pregnant in the last month (3) Eighth month: 21 pairs All 8 new rabbit pairs are pregnant, as well as those not

    pregnant in the last month (5) Ninth month: 34 pairs All 13 new rabbit pairs are pregnant, as well as those not

    pregnant in the last month (8) Tenth month: 55 pairs All 21 new rabbit pairs are pregnant, as well as those not

    pregnant in the last month (13)

  • 112

    Reproducing rabbits Note the sequence:

    { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, }

    The Fibonacci sequence again

  • 113

    Fibonacci sequence Another application:

    Fibonacci references from http://en.wikipedia.org/wiki/Fibonacci_sequence

  • 114

    Fibonacci sequence As the terms increase, the ratio between successive terms

    approaches 1.618

    This is called the golden ratio Ratio of human leg length to arm length Ratio of successive layers in a conch shell

    Reference: http://en.wikipedia.org/wiki/Golden_ratio

    618933989.12

    15)(

    )1(lim =+==+ nFnF

    n

  • 115

    The Golden Ratio

  • 116

  • 117117

    Number countingNumber counting

  • 118

    The programming assignment This was the looping HW from last fall

    Get an integer i from the user The homework had four parts Print all the Fibonacci numbers up to i Print all the powers of 2 up to i Print all the prime numbers up to i Time the previous three parts of the code

  • 119

    Sample executionInput an integer i: 10

    The 10th Fibonacci number is 55Computation took 1 ms

    2 3 5 7 11 13 17 19 23 29The 10th prime is 29Computation took 0 ms

    The 10th power of 2 is 1024Computation took 6 ms

    2 4 8 16 32 64 128 256 512 1024BigInteger: The 10th power of 2 is 1024Computation took 2 ms

  • 120

    Background: Prime numbers Remember that a prime number is a number that is ONLY

    divisible by itself and 1

    Note that 1 is not a prime number! Thus, 2 is the first prime number

    The first 10 prime numbers: 2 3 5 7 11 13 17 19 23 29

    The easiest way to determine prime numbers is with nested loops

  • 121

    How to time your code Is actually pretty easy:

    long start = System.currentTimeMillis();

    // do the computation

    long stop = System.currentTimeMillis();

    long timeTakenMS = stop-start;

    This is in milliseconds, so to do the number of actual seconds:

    double timeTakenSec = timeTakenMS / 1000.0;

  • 122122

    Program DemoProgram Demo

    NumberGames.javaNumberGames.java

    Note what happens when you enter 100Note what happens when you enter 100 With the Fibonacci numbersWith the Fibonacci numbers With the powers of 2With the powers of 2

  • 123

    BigIntegers An int can only go up to 2^31 or about 2*109 A long can only go up to 2^63, or about 9*1018 What if we want to go higher?

    2100 = 1267650600228229401496703205376

    To do this, we can use the BigInteger class It can represent integers of any size This is called arbitrary precision

    Not surprisingly, its much slower than using ints and longs

    The Fibonacci number part didnt use BigIntegers Thats why we got -980107325 for the 100th term It flowed over the limit for ints called overflow

  • 124

    BigInteger usage BigIntegers are in the java.math library import java.math.*;

    To get nn:

    BigInteger bigN = new BigInteger (String.valueOf(n));

    BigInteger biggie = new BigInteger (String.valueOf(1));

    for ( int i = 0; i < n; i++ )

    biggie = biggie.multiply (bigN);

    System.out.println (biggie);

  • 125125

    Look at that them there codeLook at that them there code

    NumberGames.javaNumberGames.java

    IterationJava loopingAveraging valuesAveragingAveragingAveragingProgram DemoWhile syntax and semanticsWhile semantics for averaging problemWhile SemanticsExecution TraceWhat do these pictures mean?Converting text to lower caseConverting text to strictly lowercaseSample runProgram DemoProgram traceProgram traceAnother optical illusionLoop Design & Reading From a FileLoop designReading a fileReading a fileReading a fileTodays demotivatorsThe For statementThe For Statementfor statement syntaxfor vs. whileVariable declarationVariable declarationExecution Tracefor vs. whilefor vs. whilefor loop indexingNested loopsNested loopsHow well do you understand for loops?From Dubaido-while loopsThe do-while statementPicking off digitsGuessing a numberProgram Demowhile vs. do-whilewhile vs. do-whileHow well do you understand do-while loops?Todays demotivatorsLoop controlsThe continue keywordThe break keywordFour HobosFour HobosProblemAnalysisImplementationProgram DemoResultsTodays demotivatorsAlternate implementationAlternate implementationHow well do you understand four hobos?The 2006 Ig Nobel Prizes3 card poker3 Card PokerThe Card classCard class methodsThe Hand classProvided Hand methodsHand Methods to ImplementClass HandEvaluationProgram DemoHow well do you understand 3-card poker?All your base are belong to usThe Halting ProblemWhats wrong with this program?The Halting problemA few notesTake your best guess do you think its possible to solve the halting problem?Can a human determine if a program halts?Halting problem examples: will they halt?Take your best guess do you think its possible to solve the halting problem?Perfect numbersOdd perfect number searchTake your best guess do you think its possible to solve the halting problem?Where does that leave us?CheckHalt()s non-existenceCheckHalt()s non-existenceCheckHalt()s non-existenceHow well do you understand the halting problem?Why do we care about the halting problem?New 2005 demotivatiors!Not going over any more slides in this slide setTriangle countingThe programming assignmentSample executionProgram DemoThe Triangle classThe TriangleDemo classLook at that them there codeHow well do you understand triangle counting?Fibonacci numbersFibonacci sequenceFibonacci sequence in natureReproducing rabbitsReproducing rabbitsReproducing rabbitsReproducing rabbitsFibonacci sequenceFibonacci sequenceThe Golden RatioNumber countingThe programming assignmentSample executionBackground: Prime numbersHow to time your codeProgram DemoBigIntegersBigInteger usageLook at that them there code