1 / 99

Iteration

Iteration. Chapter 6 Spring 2006 CS 101 Aaron Bloomfield. Java looping. Options while do-while for Allow programs to control how many times a statement list is executed. Averaging values. Averaging. Problem

villalba
Télécharger la présentation

Iteration

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Iteration Chapter 6 Spring 2006 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. 4.5 0.5 1.3 -1 Average 2.1

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

  8. int valuesProcessed = 0; double valueSum = 0; // set up the input Scanner stdin = new Scanner (System.in); // prompt user for values System.out.println("Enterpositivenumbers1perline.\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

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

  11. 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 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(); }

  12. 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 While Semantics Expression false true Action

  13. Execution Trace Suppose input contains: 4.50.51.3-1 Suppose input contains: 4.50.51.3 -1 Suppose input contains: 4.5 0.5 1.3 -1 Suppose input contains: 4.5 0.5 1.3 -1 Suppose input contains: 4.50.5 1.3 -1 valuesProcessed 1 0 3 2 4.5 valueSum 0 6.3 5.0 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); value 1.3 4.5 -1 0.5 average 2.1

  14. Warn your grandparents! • Historically, this class has been lethal to grandparents of students in the class • More often grandmothers • This happens most around test time • Although occasionally around the times a big assignment is due • See http://www.cis.gsu.edu/~dstraub/Courses/Grandma.htm

  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. An empty line was entered A Ctrl+z was entered. I t is the Windows escape sequence for indicating end-of-file Sample run

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

  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. Same Scanner class! filename is a String The File class allows access to files It’s in the java.io package Reading a file • Background Scanner fileIn = new Scanner (new File (filename) );

  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 stream Determine file name Set up file stream Process lines one by one Get first line Make sure got a line to process Display current line Get next line Make sure got a line to process If not, loop is done Close the file stream

  26. Today’s demotivators

  27. The For statement

  28. The body of the loop iterates while the test expression is Initialization step true is performed only After each iteration of the once -- just prior body of the loop, the update to the first expression is reevaluated 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 The For Statement int currentTerm = 1; for ( int i = 0; i < 5; ++i ) { System.out.println(currentTerm); currentTerm *= 2; }

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

  30. Logical test expression that determines whether the action and update step are executed Initialization step prepares for the first evaluation of the test Update step is performed after expression the execution of the loop body The body of the loop iterates whenever the test expression evaluates to true for statement syntax ForInit ForExpression ForUpdate Action for ( ; ; )

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

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

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

  34. Execution Trace i 0 2 1 3 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 for ( int i = 0; int i = 0; i < 3; i < 3; ++i ++i ) { Variable i has gone out of scope – it is local to the loop

  35. 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++; }

  36. 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++; } only difference count is NOT defined here count IS defined here

  37. 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++ ) { ... }

  38. 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 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); } }

  39. 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 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); } }

  40. Another optical illusion

  41. do-while loops

  42. Action true Expression false The do-while statement • Syntax doAction 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

  43. 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: 1129 9 2 1 1

  44. 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 );

  45. Program Demo • GuessMyNumber.java

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

  47. 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; }

  48. Today’s demotivators

  49. Loop controls

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

More Related