1 Iteration Chapter 6 Fall 2005 CS 101 Aaron Bloomfield.

Slides:



Advertisements
Similar presentations
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Advertisements

Topic 03 Control Statements Programming II/A CMC2522 / CIM2561 Bavy Li.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Introduction to Computers and Programming Lecture 8: More Loops New York University.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
1 Review for Midterm 3 CS 101 Spring Topic Coverage  Loops Chapter 4  Methods Chapter 5  Classes Chapter 6, Designing and creating classes.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Chapter 4: Control Structures II
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
Java Programming: From the Ground Up
Chapter 5 Loops.
October 28, 2015ICS102: For Loop1 The for-loop and Nested loops.
1 Iteration. 2 Java looping  Options while do-while for  Allow programs to control how many times a statement list is executed.
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
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.
Chapter 4: Control Structures II
Chapter 5: Control Structures II
Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Iteration. Java looping Options –while –do-while –for Allow programs to control how many times a statement list is executed.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved5-2 The switch Statement The switch statement provides another way.
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
1 Methods Chapter 5 Spring 2007 CS 101 Aaron Bloomfield.
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
1 Iteration Chapter 6 Fall 2006 CS 101 Aaron Bloomfield.
1 Iteration. 2 Java looping  Options while do-while for  Allow programs to control how many times a statement list is executed.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 5 Control Structures II: Repetition.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Feedback  Lab2, Hw1  Groups  Group Project Requirements.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
Programming in Java (COP 2250) Lecture 12 & 13 Chengyong Yang Fall, 2005.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Chapter 6 More Conditionals and Loops
Chapter 5: Control Structures II
Loop Structures.
Repetition-Counter control Loop
Repetition-Sentinel,Flag Loop/Do_While
Chapter 4 – Control Structures Part 1
Lecture 07 More Repetition Richard Gesick.
Chapter 5: Control Structures II
Lecture 4B More Repetition Richard Gesick
Iteration.
Outline Altering flow of control Boolean expressions
Iteration.
Review for Midterm 3.
Review for Midterm 3.
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS
Truth tables: Ways to organize results of Boolean expressions.
Repetition Statements
Review for Midterm 3.
Presentation transcript:

1 Iteration Chapter 6 Fall 2005 CS 101 Aaron Bloomfield

2 Java looping  Options while do-while for  Allow programs to control how many times a statement list is executed

3 Averaging values

4 Averaging  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  Don’t how big of a list to process Need ability to repeat code as needed

5 Averaging  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

6 Averaging  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 run Enter positive numbers one per line. Indicate end of list with a negative number Average 2.1

public class NumberAverage { // main(): application entry point public static void main(String[] args) { // set up the input // prompt user for values // get first value // process values one-by-one while (value >= 0) { // add value to running total // processed another value // prepare next iteration - get next value } // display result if (valuesProcessed > 0) // compute and display average else // 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"); }

9 Program Demo NumberAverage.java NumberAverage.java

10 Today’s dose of demotivators

11 While syntax and semantics Logical expression that determines whether Action is to be executed while ( Expression ) Action Action is either a single statement or a statement list within braces

12 While semantics for averaging problem // process values one-by-one while ( value >= 0 ) { // add value to running total valueSum += value; // we processed another value ++valueProcessed; // prepare to iterate – get the next input value = stdin.nextDouble(); } Test expression is evaluated at the start of each iteration of the loop. If test expression is true, these statements are executed. Afterward, the test expression is reevaluated and the process repeats

13 While Semantics Expression Action true false Expression is evaluated at the start of each iteration of the loop If Expression is true, Action is executed If Expression is false, program execution continues with next statement

14 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 Trace Suppose input contains: valuesProcessed valueSum 0 value 4.5 Suppose input contains: Suppose input contains: Suppose input contains: Suppose input contains: average 2.1

15 Converting text to lower case

16 Converting text to strictly lowercase 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); }

17 Sample run A Ctrl+z was entered. It is the Windows escape sequence for indicating end-of-file An empty line was entered

18 Program Demo LowerCaseDisplay.java LowerCaseDisplay.java

19 Program trace 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); } 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 case conversion of current input line converted += (currentConversion + "\n"); The append assignment operator updates the representation of converted to include the current input line Newline character is needed because method nextLine() "strips" them from the input

21 Loop Design & Reading From a File

22 Loop design  Questions to consider in loop design and analysis What initialization is necessary for the loop’s test expression? What initialization is necessary for the loop’s 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?

23 Reading a file  Background Same Scanner class! Scanner fileIn = new Scanner (new File (filename) ); The File class allows access to files It’s in the java.io package filename is a String

24 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

25 Reading a file 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(); } 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 process If not, loop is done Close the file stream

26 All your base are belong to us All your base history: All your base history: Flash animation: B2.swf Flash animation: B2.swf B2.swf B2.swf

27 End of lecture on 5 October 2005  Also went over:  Lab 6  HW J4  Mid semester review results

28 The 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 the body of the loop, the update expression is reevaluated The body of the loop iterates while the test expression is true int Initialization step is performed only once -- just prior to the first evaluation of the test expression The body of the loop displays the current term in the number series. It then determines what is to be the new current number in the series

ForExpr Action truefalse ForInit PostExpr Evaluated once at the beginning of the for statements's execution The ForExpr is evaluated at the start of each iteration of the loop If ForExpr is true, Action is executed After the Action has completed, the PostExpression is evaluated If ForExpr is false, program execution continues with next statement After evaluating the PostExpression, the next iteration of the loop starts

31 for statement syntax Logical test expression that determines whether the action and update step are executed for ( ForInit ; ForExpression ; ForUpdate ) Action Update step is performed after the execution of the loop body Initialization step prepares for the first evaluation of the test expression The body of the loop iterates whenever the 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! We’ll see when they are different below

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 Execution Trace i 0 int 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 <= 10; i++ ) {... }

39 Nested loops int 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 loops int 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 Agricultural history Agricultural history Physics Physics Medicine Medicine Literature Literature Peace Peace Economics Economics Chemistry Chemistry Biology Biology Nutrition Nutrition Fluid dynamics Fluid dynamics The 2005 Ig Nobel Prizes “The Significance of Mr. Richard Buckley’s Exploding Trousers” The pitch drop experiment, started in 1927 Neuticles – artificial replacement testicles for dogs The 409 scams of Nigeria for a “cast of rich characters” Locust brain scans while they were watching Star Wars For an alarm clock that runs away, thus making people more productive “Will Humans Swim Faster or Slower in Syrup?” For cataloging the odors of 131 different stressed frogs To Dr. Yoshiro Nakamats who catalogued and analyzed every meal he ate for the last 34 years (and counting) “Pressures Produced When Penguins Pooh – Calculations on Avian Defaecation”

42 do-while loops

43 The do-while statement  Syntax do Action while (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

44 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 behavior Enter a positive number:

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

46 Program Demo GuessMyNumber.java GuessMyNumber.java

47 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

48 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; }

49 Hand Paintings

50 Loop controls

51 The continue keyword  The continue keyword will immediately start the next iteration of the loop The rest of the current loop is not executed for ( int a = 0; a <= 10; a++ ) { if ( a % 2 == 0 ) { continue; } System.out.println (a + " is odd"); }  Output:1 is odd 3 is odd 5 is odd 7 is odd 9 is odd

52 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 <= 10; a++ ) { if ( a == 5 ) { break; } System.out.println (a + " is less than five"); }  Output:0 is less than five 1 is less than five 2 is less than five 3 is less than five 4 is less than five

53 Four Hobos

54 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 NPR’s Sunday Morning Edition puzzle person  This problem is in section 6.10 of the text

55 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?

56 Analysis  We are looking for integer solutions to the formula: a 2 +b 2 +c 2 +d 2 = 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 doesn’t 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

57 Implementation public class FourHobos { public static void main (String[] args) { for ( int a = 1; a <= 14; a++ ) { for ( int b = 1; b <= 14; b++ ) { for ( int c = 1; c <= 14; c++ ) { for ( int d = 1; d <= 14; d++ ) { if ( (a <= b) && (b <= c) && (c <= d) ) { if ( a*a+b*b+c*c+d*d == 200 ) { System.out.println ("(" + a + ", " + b + ", " + c + ", " + d + ")"); }

58 Program Demo FourHobos.java FourHobos.java

59 Results  The output: (2, 4, 6, 12) (6, 6, 8, 8)  Not surprisingly, the smart hobo picks the short straw of the first combination

60 Alternate implementation  We are going to rewrite the old code in the inner most for loop: if ( (a <= b) && (b <= c) && (c <= d) ) { if ( a*a+b*b+c*c+d*d == 200 ) { System.out.println ("(" + a + ", " + b + ", " + c + ", " + d + ")"); } }  First, consider the negation of ( (a <= b) && (b <= c) && (c <= d) ) It’s ( !(a <= b) || !(b <= c) || !(c <= d) ) Or ( (a > b) || (b > c) || (c > d) )

61 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 + ")");

62 Today’s demotivators

63 End of lecture on 10 October 2005

64 3 card poker

65 3 Card Poker  This is the looping HW from last 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 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

66 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 then a card is configured in the following manner  If 1 <= i <= 13 then the card is a club  If 14 <= i <= 26 then the card is a diamond  If 27 <= i <= 39 then the card is a heart  If 40 <= i <= 52 then the card is a spade  If i % 13 is 1 then the card is an Ace;  If i % 13 is 2, then the card is a 2, and so on.

67 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.

68 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

69 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() We’ll 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

70 Hand Methods to Implement  The assignment required the students to implement the other methods of the Hand class We haven’t seen this yet  The methods returned true if the Hand contained a “winning” combination of cards public boolean isPair() public boolean isThree() public boolean isStraight() public boolean isFlush() public boolean isStraightFlush()

71 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

72 Program Demo HandEvaluation.java HandEvaluation.java

73 Today’s demotivators