123
1 Iteration Chapter 4 pt. 2 Trey Kirk

1 Iteration Chapter 4 pt. 2 Trey Kirk. 2 Java looping Options while do-while for Allow programs to control how many times a statement list is executed

Embed Size (px)

Citation preview

  • *IterationChapter 4 pt. 2Trey Kirk

  • *Java loopingOptionswhiledo-whilefor

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

  • *Averaging values

  • *AveragingProblemExtract a list of positive numbers from standard input and produce their averageNumbers are one per lineA negative number acts as a sentinel to indicate that there are no more numbers to process

    ObservationsCannot supply sufficient code using just assignments and conditional constructs to solve the problemDont how big of a list to processNeed ability to repeat code as needed

  • *AveragingAlgorithmPrepare for processingGet first inputWhile there is an input to process do {Process current inputGet the next input}Perform final processing

  • *AveragingProblemExtract a list of positive numbers from standard input and produce their averageNumbers are one per lineA 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.50.51.3-1Average 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 inputScanner stdin = new Scanner (System.in);

    // prompt user for valuesSystem.out.println("Enter positive numbers 1 per line.\n" + "Indicate end of the list with a negative number.");

    // get first valuedouble value = stdin.nextDouble();

    // process values one-by-onewhile (value >= 0) {valueSum += value;++valuesProcessed;value = stdin.nextDouble();}

    // display resultif (valuesProcessed > 0) {double average = valueSum / valuesProcessed;System.out.println("Average: " + average);} else {System.out.println("No list to average");}

  • *Program DemoNumberAverage.java

  • *While syntax and semanticswhile ( Expression ) Action

  • *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();}

  • *While SemanticsExpressionActiontruefalse

  • *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);

    Execution TraceSuppose input contains: 4.5 0.5 1.3 -10valuesProcessedvalueSum0value4.5Suppose input contains: 4.5 0.5 1.3 -14.51Suppose input contains: 4.5 0.5 1.3 -10.55.021.36.3Suppose input contains: 4.5 0.5 1.3 -13-1Suppose input contains: 4.5 0.5 1.3 -1average2.1

  • *What do these pictures mean?Light beerDandy lionsAssaulted peanutEggplantDr. PepperPool tableTap dancersCard sharkKing of popI PodGator aideKnight mareHole milk

  • *Converting text to lower case

  • *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);}

  • *Sample run

  • *Program DemoLowerCaseDisplay.java

  • *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);}

  • *Program traceconverted += (currentConversion + "\n");

  • *Another optical illusion

  • *Loop Design & Reading From a File

  • *Loop designQuestions 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?

  • *Reading a fileBackgroundScanner fileIn = new Scanner (new File (filename) );

  • *Reading a fileClass FileAllows access to files (etc.) on a hard drive

    Constructor File (String s)Opens the file with name s so that values can be extractedName can be either an absolute pathname or a pathname relative to the current working folder

  • *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

  • *Todays demotivators

  • *End of lecture on 23 February 2007

  • *The For statement

  • *The For StatementcurrentTerm = 1;for ( int i = 0; i < 5; ++i ) {System.out.println(currentTerm);currentTerm *= 2;}int

  • ForExprActiontruefalseForInitForUpdate

  • *for statement syntaxfor ( ForInit ; ForExpression ; ForUpdate ) Action

  • *for vs. whileA 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

  • *Variable declarationYou 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 timeThus, println() always prints out 1Variable n is not defined once while loop endsAs n is not defined here, this causes an error

  • *Variable declarationYou 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

  • *

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

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

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

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

    i is 0i is 1i is 2all done

    Execution Tracei0int i = 0;i < 3;++ifor () {int i = 0;i < 3;++i123Variable i has gone out of scope itis local to the loop

  • *for vs. whileAn 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++;}

  • *for vs. whileAn 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 herecount is NOT defined hereonly difference

  • *for loop indexingJava (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

  • *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 1i is 1 j is 0 j is 1i is 2 j is 0 j is 1

  • *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 0i is 1 j is 0i is 2 j is 0 j is 1i is 3j is 0j is 1j is 2

  • *How well do you understand for loops?Very well! This stuff is easy!Fairly well with a little review, Ill be goodOkay. Its not great, but its not horrible, eitherNot well. Im kinda confusedNot at all. Im soooooo lost

  • *From Dubai

  • *do-while loops

  • *The do-while statementSyntaxdo Action while (Expression)SemanticsExecute ActionIf Expression is true then execute Action againRepeat this process until Expression evaluates to falseAction is either a single statement or a group of statements within braces

  • *Picking off digitsConsiderSystem.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: 11299211

  • *Guessing a numberThis 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 );

  • *Program DemoGuessMyNumber.java

  • *while vs. do-whileIf the condition is false:while will not execute the actiondo-while will execute it once

    while ( false ) {System.out.println (foo);}

    do {System.out.println (foo);} while ( false );never executedexecuted once

  • *while vs. do-whileA 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;}

  • *How well do you understand do-while loops?Very well! This stuff is easy!Fairly well with a little review, Ill be goodOkay. Its not great, but its not horrible, eitherNot well. Im kinda confusedNot at all. Im soooooo lost

  • *Todays demotivators

  • *End of lecture on 26 February 2007

  • *Loop controls

  • *The continue keywordThe continue keyword will immediately start the next iteration of the loopThe rest of the current loop is not executedBut the ForUpdate part is, if continue is in a for loop

    for ( int a = 0; a

  • *The break keywordThe break keyword will immediately stop the execution of the loopExecution resumes after the end of the loop

    for ( int a = 0; a

  • *Four Hobos

  • *Four HobosAn example of a program that uses nested for loops

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

  • *ProblemFour hobos want to split up 200 hours of workThe smart hobo suggests that they draw straws with numbers on itIf a straw has the number 3, then that hobo works for 3 hours on 3 days each (a total of 9 hours)How many combinations are there to split up such work?The smart hobo draws the shortest strawWhich combination did the smart hobo choose?

  • *AnalysisWe are looking for integer solutions to the formula:a2+b2+c2+d2 = 200Where 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 1No number can be greater than 200 = 14That order doesnt matterThe 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

  • *Implementationpublic class FourHobos {

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

  • *Program DemoFourHobos.java

  • *ResultsThe output:(2, 4, 6, 12)(6, 6, 8, 8)

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

  • *Todays demotivators

  • *Alternate implementationWe are going to rewrite the old code in the inner most for loop:

    if ( (a

  • *Alternate implementationThis 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 + ")");

  • *3 card poker

  • *3 Card PokerThis is the looping HW from a previous fallThe 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, hearts13 Faces: Ace, 2 through 10, Jack, Queen, King

    Possible 3-card poker handsPair: two of the cards have the same face valueFlush: all the cards have the same suitStraight: the face values of the cards are in successionThree of a kind: all three cards have the same face valueStraight flush: both a flush and a straight

  • *The Card classA Card class was providedRepresents 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 mannerIf 1

  • *Card class methodsString 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.

  • *The Hand classA Hand class was (partially) providedRepresents the three cards the player is holding

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

  • *Provided Hand methodspublic Card getLow()Gets the low card in the handpublic Card getMiddle()Gets the middle card in the handpublic Card getHigh()Gets the high card in the handpublic String toString()Well see the use of the toString() method laterpublic 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

  • *Hand Methods to ImplementThe assignment required the students to implement the other methods of the Hand classWe havent seen this yet

    The methods returned true if the Hand contained a winning combination of cardspublic boolean isPair()public boolean isThree()public boolean isStraight()public boolean isFlush()public boolean isStraightFlush()

  • *Class HandEvaluationRequired nested for loops to count the total number of each hand

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

  • *Program DemoHandEvaluation.java

  • *How well do you understand 3-card poker?Very well! This stuff is easy!Fairly well with a little review, Ill be goodOkay. Its not great, but its not horrible, eitherNot well. Im kinda confusedNot at all. Im soooooo lost

  • *All your base are belong to us

    Flash animationReference: http://en.wikipedia.org/wiki/All_your_base_are_belong_to_us

  • *End of lecture on 28 Feb 2007Class was optional on 2 March 2007Then spring break

  • *The Halting Problem

  • *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?

  • *

  • *The Halting problemGiven a Java program P, and input ILet P be a filename for a program file on a disk somewhereLet 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 1936Before digital computers existed!(Im ignoring which way he showed it for now)

  • *A few notesTo 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) answersOracle.PredictFuture(), Oracle.GetNextLotteryNumbers(), etc.P is the (filename of the) program we are checking for haltingI is the (filename of the) input to that programAnd it will return loops forever or haltsAs a boolean: true means loops forever, false means haltsNote it must work for any (Java) program, not just some programsOr simple programs

  • *Take your best guess do you think its possible to solve the halting problem?YesNoI dont understand what the halting problem is

  • *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 understandableAnd assuming the computer works properly, of course

    And we ignore the fact that an int will max out at 4 billionAs 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 classAssume print stands for System.out.printLikewise for println

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

  • *Take your best guess do you think its possible to solve the halting problem?YesNoI dont understand what the halting problem is

  • *Perfect numbersNumbers whose divisors (not including the number) add up to the number6 = 1 + 2 + 328 = 1 + 2 + 4 + 7 + 14The list of the first 10 perfect numbers: 6, 28, 496, 8128, 33550336, 8589869056, 137438691328, 2305843008139952128, 2658455991569831744654692615953842176, 191561942608236107294793378084303638130997321548169216The last one was 54 digits!All known perfect numbers are even; its an open (i.e. unsolved) problem if odd perfect numbers existSequence A000396 in OEIS

  • *Odd perfect number searchWill this program ever halt?

    int n = 1; // arbitrary-precision integer while (true) { int sumOfFactors = 0; for ( int factor = 1; factor < n; factor++ ) if ( n % factor == 0 ) // factor is a factor of n sumOfFactors = sumOfFactors + factor; if (sumOfFactors == n) then break; n = n + 2; } System.out.exit();

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

  • *Take your best guess do you think its possible to solve the halting problem?YesNoI dont understand what the halting problem is

  • *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() methodBut how to prove this?

  • *CheckHalt()s non-existenceConsider a program P with input ISuppose that a method Oracle.CheckHalt(P,I) existsTests if P(I) will either loop forever or haltA program is a series of bitsAnd thus can be considered data as wellThus, we can call CheckHalt(P,P)Its using the bytes of program P as the input to program P

  • *CheckHalt()s non-existenceConsider a new program:

    public class Test {public static void main (String args[]) {if ( Oracle.CheckHalt(Test.java, Test.java) )// if Test.java loops foreverSystem.exit();// then haltelse// else if Test.java haltswhile (true) { }// then loop forever}}

    Do we agree that class Test is a valid program?

  • *CheckHalt()s non-existenceA (somewhat condensed) version of class Test:

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

    if ( Oracle.CheckHalt (Test.java, Test.java) )System.exit(); elsewhile (true) { } }}

    Two possibilities:

    Either class Test haltsThen CheckHalt(Test,Test) returns true (loops forever)Which means that class Test loops foreverContradiction!

    Or class Test loops foreverThen CheckHalt(Test,Test) returns false (halts)Which means that class Test haltsContradiction!

  • *How well do you understand the halting problem?Very well! This stuff is easy!Fairly well with a little review, Ill be goodOkay. Its not great, but its not horrible, eitherNot well. Im kinda confusedNot at all. Im soooooo lost

  • *Why do we care about the halting problem?

    It was the first algorithm that was shown to not be able to exist by a computerYou 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 1936Before digital computers existed!

  • *New 2005 demotivatiors!

  • *Not going over any more slides in this slide set

  • *Triangle counting

  • *The programming assignmentThis 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 numberIn particular, list their triangle type

    Types are: equilateral, isosceles, right, and scalene

  • *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

  • *Program DemoTriangleDemo.java

  • *The Triangle classThat semester we went over classes by this homeworkSo they had to finish the classWe 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()

  • *The TriangleDemo classContained 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 lengthsCreate a new Triangle object using the current side lengthsCheck if it is a valid triangleIf it is not, then no output should be provided for that collection of side lengthsOtherwise, indicate which properties the triangle possessesSome side length values will correspond to more than 1 trianglee.g., (3, 3, 3) is both isosceles and equilateralThus, we cant assume that once a property is present, the others are not.

  • *Look at that them there codeTriangleDemo.java

  • *How well do you understand triangle counting?Very well! This stuff is easy!Fairly well with a little review, Ill be goodOkay. Its not great, but its not horrible, eitherNot well. Im kinda confusedNot at all. Im soooooo lost

  • *Fibonacci numbers

  • *Fibonacci sequenceSequences can be neither geometric or arithmeticFn = Fn-1 + Fn-2, where the first two terms are 1Alternative, F(n) = F(n-1) + F(n-2)Each term is the sum of the previous two termsSequence: { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, }This is the Fibonacci sequence

    Full formula:

  • *Fibonacci sequence in nature1385321

  • *Reproducing rabbitsYou have one pair of rabbits on an islandThe rabbits repeat the following:Get pregnant one monthGive birth (to another pair) the next monthThis process repeats indefinitely (no deaths)Rabbits get pregnant the month they are born

    How many rabbits are there after 10 months?

  • *Reproducing rabbitsFirst month: 1 pairThe original pairSecond month: 1 pairThe original (and now pregnant) pairThird month: 2 pairsThe child pair (which is pregnant) and the parent pair (recovering)Fourth month: 3 pairsGrandchildren: Children from the baby pair (now pregnant)Child pair (recovering)Parent pair (pregnant)Fifth month: 5 pairsBoth the grandchildren and the parents reproduced3 pairs are pregnant (child and the two new born rabbits)

  • *Reproducing rabbitsSixth month: 8 pairsAll 3 new rabbit pairs are pregnant, as well as those not pregnant in the last month (2)Seventh month: 13 pairsAll 5 new rabbit pairs are pregnant, as well as those not pregnant in the last month (3)Eighth month: 21 pairsAll 8 new rabbit pairs are pregnant, as well as those not pregnant in the last month (5)Ninth month: 34 pairsAll 13 new rabbit pairs are pregnant, as well as those not pregnant in the last month (8)Tenth month: 55 pairsAll 21 new rabbit pairs are pregnant, as well as those not pregnant in the last month (13)

  • *Reproducing rabbitsNote the sequence:{ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, }

    The Fibonacci sequence again

  • *Fibonacci sequenceAnother application:

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

  • *Fibonacci sequenceAs the terms increase, the ratio between successive terms approaches 1.618

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

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

  • *The Golden Ratio

  • *

  • *Number counting

  • *The programming assignmentThis was the looping HW from last fall

    Get an integer i from the userThe homework had four partsPrint all the Fibonacci numbers up to iPrint all the powers of 2 up to iPrint all the prime numbers up to iTime the previous three parts of the code

  • *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

  • *Background: Prime numbersRemember 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

  • *How to time your codeIs actually pretty easy:

    long start = System.currentTimeMillis();// do the computationlong stop = System.currentTimeMillis();long timeTakenMS = stop-start;

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

    double timeTakenSec = timeTakenMS / 1000.0;

  • *Program DemoNumberGames.java

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

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

    2100 = 1267650600228229401496703205376

    To do this, we can use the BigInteger classIt can represent integers of any sizeThis is called arbitrary precisionNot surprisingly, its much slower than using ints and longs

    The Fibonacci number part didnt use BigIntegersThats why we got -980107325 for the 100th termIt flowed over the limit for ints called overflow

  • *BigInteger usageBigIntegers are in the java.math libraryimport 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);

  • *Look at that them there codeNumberGames.java

    Sentinel values that have certain values that indicate a change in the iteration. Usually, it indicates the iteration needs to stopObservations for example, you could use three variables if you knew there were going to be a list of three values. However, the list in this situation is determined at runtime by the user*What do you suppose happens during the process current input? And what about final processing?**Roadmap for program*The role of valuesProcessed is to indicate how many values have been processed. Because no values have been processed yet, valuesProcessed is initialized to 0. Variable valueSum maintains the running total of the input values processed so far. Therefore, it is initialized to 0.

    By properly updating variables valuesProcessed and valueSum whenever an input value is extracted, the average of the inputs can be computed. The average will be equal to valueSum / valuesProcessed.

    The program next issues a prompt that tells the user both how to supply the values and how to indicate that there are no more values to consider. In particular, the user is told that positive numbers are to be entered, one per line. The user is also told that a negative number means that the list is complete. In programming parlance, this end of list value is called a sentinel.

    The first value is extracted before the loop. The value is extracted before the while loop because the statements that make up the action of a loop have been designed to process a list value. They are not intended for dealing with the sentinel.

    *When a while statement is executed, its test expression is evaluated first. If the expression evaluates true, its body is executed, where the body is the action of the while statement. The evaluation process then is repeated. If the expression reevaluates to true, the body is executed again. This process is called looping, and it continues until the test expression evaluates to false. At that point, execution continues with the next statement in the program.

    *When a while statement is executed, its test expression is evaluated first. If the expression evaluates true, its body is executed, where the body is the action of the while statement. The evaluation process then is repeated. If the expression reevaluates to true, the body is executed again. This process is called looping, and it continues until the test expression evaluates to false. At that point, execution continues with the next statement in the program.

    *The tracing of the execution of a method by hand is an important program debugging technique. Hand-checking code can give insight into how a method works.

    *An empty line is not an indication that no text is being provided. Instead, an empty line corresponds to an empty string. To indicate that no more text is being provided, the user must enter an operating system-dependent escape sequence (sentinel). The Windows sentinel value is Ctrl+z and for most other operating systems it is Ctrl+d. For historic reasons regarding earlier programming languages, software developers commonly refer to the sentinel value as end-of-file.

    *If the user provides text, then currentLine is initialized with the first line from the standard input stream. If instead, the user indicates that they are not providing an input, then currentLine is initialized with the value null

    **is part of the action associated with the for loop that begins on the third line of the segment. We say that this loop is the outer loop. The expression i < n that controls the iteration of the loop evaluates to true three times with i taking on in turn the values 0, 1, and 2. Thus, there are three lines of output that begin with iis. Each time there is such a display, the for loop beginning on the fifth line of the segment is executed. We say this loop is an inner or nested loop.

    It is important to realize that an inner loop starts up once per iteration of its outer loop. For our example, each time the inner loop is executed, the expression j