1 / 65

Introduction to Computer Science

Introduction to Computer Science. Unit 13. More on Loops and Bounds One dimensional Two dimensional. Three Parts to a Loop. Every loop has three parts: A goal that states the loop’s purpose A bound that gives the reason the loop will end

melba
Télécharger la présentation

Introduction to Computer Science

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. Introduction to Computer Science Unit 13 More on Loops and Bounds • One dimensional • Two dimensional

  2. Three Parts to a Loop Every loop has three parts: • A goal that states the loop’s purpose • A bound that gives the reason the loop will end • A plan that describes the action the loop is going to take These are connected becauseyou make them connected.

  3. Example Goal: To know the sum, and number, of a series of input numbers; Bound: We’ve read a negative number; Plan: Read a number. Add it to a running sum. Add one to a counter. The loop’s goal and bound are distinct. Take the smallest step necessary to approach the bound. Frequently, the step must be taken before the loop as well as within the loop. Then, and only if necessary, add additional steps that help reach the loop’s goal.

  4. Example • i = sinp.readInt( ); • while (i >= 0) { • total = total + i; • counter++; • i = sinp.readInt( ); • } “Read a number” brings us towards the bound. The step is taken before the loop, then again before each repetition.

  5. Questions • Given a goal, invent a bound and plan:

  6. Questions • Given a goal, invent a bound and plan: a) Goal: Skip 50 input numbers. Bound: A counter equals 50. Plan: Add 1 to counter that started at 0. Read a value.

  7. Questions • Given a goal, invent a bound and plan: a) Goal: Skip 50 input numbers. Bound: A counter equals 50. Plan: Add 1 to counter that started at 0. Read a value. b) Goal: Find the position of the letter F in an array of chars that includes an F.

  8. Questions • Given a goal, invent a bound and plan: a) Goal: Skip 50 input numbers. Bound: A counter equals 50. Plan: Add 1 to counter that started at 0. Read a value. b) Goal: Find the position of the letter F in an array of chars that includes an F. Bound: Reading the letter F. Plan: Read a value. Add one to an array index counter.

  9. More Questions c) Goal: Divide 35 by 6 using subtraction.

  10. More Questions c) Goal: Divide 35 by 6 using subtraction. Bound: The remainder is less than 6. Plan: Subtract 6 from the current remainder. Add 1 to the quotient.

  11. More Questions c) Goal: Divide 35 by 6 using subtraction. Bound: The remainder is less than 6. Plan: Subtract 6 from the current remainder. Add 1 to the quotient. d) Goal: Count the number of F’s in an input word.

  12. More Questions c) Goal: Divide 35 by 6 using subtraction. Bound: The remainder is less than 6. Plan: Subtract 6 from the current remainder. Add 1 to the quotient. d) Goal: Count the number of F’s in an input word. Bound: Reading a space character. Plan: Read a character. Add 1 to a counter if the character is an F.

  13. And One More! e) Goal: Print an integer in reverse.

  14. And One More! e) Goal: Print an integer in reverse. Bound: The number has been reduced to zero. Plan: Print the one’s digit by printing the number % 10. ‘Strip off’ the one’s digit by recalculating the number / 10.

  15. Example: count components whose subscripts equal value stored int[ ] sequence = new int[10]; int count = 0; for (int subscript = 0;subscript < sequence.length; subscript++) { if (sequence[subscript] == subscript) count++; }

  16. Example: find largest stored value and its location int[ ] sequence = new int[10]; int bigPos = 0; for (int subscript = 1; subscript < sequence.length; subscript++) { if (sequence[subscript] > sequence[bigPos]) bigPos = subscript; } System.out.print(“The biggest value, ”); System.out.print(sequence[bigPos]); System.out.print(“, was in component ”); System.out.println(bigPos);

  17. Loops and Their Bounds • Four reasons we want a loop to stop: • A sentinel or marker value was encountered (e.g., a blank space) • A count was attained (the loop has repeated a certain number of times) • A limit was reached (we’ve gotten as close as necessary to the answer) • The data was used up

  18. Different Ways to Do It • Our goal may be to add numbers. Our bound can be a: • sentinel (add numbers until getting a negative one); • count (add ten numbers); • limit (add numbers until the total exceeds 500); • data bound (if we add numbers until there are no more).

  19. Loops: while vs. for • A while loop is appropriate when our bound is defined by a sentinel, a value that marks the end of our processing • Sometimes we’ll combine our watching for a sentinel value with a count as a “backup” (in case the sentinel doesn’t appear) • Then we have to check which reason caused us to exit the loop (sentinel or count)

  20. Example of Sentinel Loop System.out.print(“Enter score (eof ends data): ”);score = sinp.readInt( );while ( !sinp.eof( ) ) { numberOfScores++; sumOfScores = sumOfScores + score; System.out.print(“Enter score (eof ends data): ”); score = sinp.readInt( );} Keep looping until we come to the sentinel: in this case, the end-of-file character from the user.

  21. Count Bounds When count bounds are used: • Counting repetitions • Counting data items • Counting events (e.g., input of correct answers) • Providing an upper limit on iteration.

  22. The General Form • initialize a counter; • (for loop) repeat untilthe count is reached or exceeded, as appropriate { • take an action; • }

  23. Loops: while vs. for A for loop is appropriate when our bound is defined by a count; we expect to loop n times, where n is a known quantity (like the asterisk printing examples) for (int i = 1; i<=10; i++) {for (int j = 1; j <= i; j++) System.out.print(“*”); System.out.println( );}

  24. Example of Sentinel Loop with Count as Backup final int NUM_SCORES = 10;int i = 0;int[ ] scores = newint[NUM_SCORES];…System.out.print(“Enter score (eof ends data): ”);scores[i] = sinp.readInt( );i++;while ( !sinp.eof( ) && (i < NUM_SCORES) ) { System.out.print(“Enter score (eof ends data): ”); scores[i] = sinp.readInt( ); i++;} Keep looping until we come to the sentinel, eof, or i hits NUM_SCORES; after the loop, we might need to check whether i = NUM_SCORES.

  25. Limit Bounds When limit bounds are used: • Loops that reduce a number to zero or to less than some known value • Successive approximation methods • Bisection methods • Non-convergence tests.

  26. Example: what does it do? Goal: ??? Bound: number equals 0 Plan: Add 1 to a counter that began at 0. Divide number by 10. • digits = 0; • while (number != 0) { • number = number / 10; • digits++; • }

  27. Example: what does it do? Goal: ??? Bound: number equals 0 Plan: Add 1 to a counter that began at 0. Divide number by 10. • digits = 0; • while (number != 0) { • number = number / 10; • digits++; • } Count number of digits in number (assumed non-zero).

  28. Data Bounds • Searching through organized collections of values • Reorganizing stored data according to bounds that aren’t fixed • Working with sequences of values (usually characters) whose end isn’t marked by a sentinel.

  29. Example: Binary Search • Look at the value falling in the middle • If it’s not the value we are looking for, we’ve established a new lower or upper bound on the search • Repeat 1 Find one value out of thirty million by inspecting, at most, 25 names.

  30. Example: Binary Search • Look at the value falling in the middle • If it’s not the value we are looking for, we’ve established a new lower or upper bound on the search • Repeat 1 2 Find one value out of thirty million by inspecting, at most, 25 names.

  31. Example: Binary Search • Look at the value falling in the middle • If it’s not the value we are looking for, we’ve established a new lower or upper bound on the search • Repeat 3 1 2 Find one value out of thirty million by inspecting, at most, 25 names.

  32. Example: Binary Search • Look at the value falling in the middle • If it’s not the value we are looking for, we’ve established a new lower or upper bound on the search • Repeat 3 1 4 2 Find one value out of thirty million by inspecting, at most, 25 names.

  33. Example: Binary Search • Look at the value falling in the middle • If it’s not the value we are looking for, we’ve established a new lower or upper bound on the search • Repeat 5 3 1 4 2 Find one value out of thirty million by inspecting, at most, 25 names.

  34. Checking Values: Try, Try Again do { System.out.print(“Pick number between 1 and 10:”); number = sinp.readInt( ); } while ( (number < 1) || (number > 10) ); //number is in the range 1…10 after loop.

  35. Traveling through aTwo-Dimensional Array As you know, to travel through a two-dimensional array, we need a nested loop: • for each row in the array • for each component (or column) in that row • inspect or process the current component; • report on the results;

  36. Example: print subscripts of every ‘17’ in 2-dimensional array “A” // Search the entire array for every ‘17’ System.out.println(“17 is stored in locations: ”); for (int row = 0; row < A.length; row++)for (int col = 0; col < A[row].length; col++) if (A[row][col] == 17) System.out.println(row + “, ” + col);

  37. Traveling an Array by Column In Java, the first subscript names the row, while the second identifies a column in that row. So the following code traverses a two-dimensional array column-by-column instead of row-by-row: • for (int col = 0; col < COLLEN; col++) { • for (int row = 0; row < ROWLEN; row++) { • inspect A[row][col] • } // inner, row-by-row for • } //outer, column-by-column for • report on the results

  38. Example: Visit a CheckerboardStopping only on colored squares • for (int row = 0; row < 8; row++) { // visit each row • if ( (row % 2) == 0 ) • start = 0; • else start =1; // even or odd • for (int col = 0; col <= 3; col++) { • visit board[row][start + (2*col)]; • } // column-by-column for • } // row-by-row for

  39. Two-DimensionalSentinel Bounds • We may find the sentinel and stop the loop before we visit the whole array • find the location of a particular value • process words or sentences stored in an array (with spaces or punctuation marks acting as sentinels) • locating a subsequence with a particular characteristic • When searching for a sentinel, a count bound will be needed as well (in case the sentinel isn’t found)

  40. The Standard (one-dimensional) pseudocode for sentinel search initialize the subscript counter; while we haven’t reached the sentinel&& we haven’t hit the end of the array { add 1 to the subscript counter } // end of the loop decide why we left the loop

  41. Example: find first number greater than 0 in one-dimensional array current = 0; // the subscript also acts as a counter while ( (sequence[current] <= 0) && (current < (sequence.length - 1)) ) { current++; } // Postcondition: If sequence[current] isn’t greater than zero, // no component is if (sequence[current] <= 0) System.out.println(“No value exceeded zero.”); else System.out.println(“Found it!”);

  42. A Subtle Point • Why do we have “sequence.length - 1”? • while ( (sequence[current] <= 0) • && (current < (sequence.length - 1)) ) { • current++; • } In this loop, we want the index “current” to end up as the last cell in the array (the value of current is to be used outside the loop), not to pass the end of the array.

  43. The two-dimensionalsearch for sentinel case Goal: Find the position of the number ‘17’. Intentional bound: Spotting the sentinel. Necessary bound: Reaching the last component of the array. Plan: Advance to the next component. This is different in the two-dimensional case.

  44. The two-dimensional case pseudocode initialize the subscript counters; while (we haven’t found the sentinel && we haven’t reached end of array) { if we haven’t reached the last column in the current row advance to the next component in this row else advance to first component in the next row } // end of the loop decide why we left the loop

  45. The Java Code(2-dimensional search for sentinel) // Search the two-dimensional A array for the first ‘17’ int col = 0; int row = 0; // Prepare to inspect the first component while ( (A[row][col] != 17) && ( (row < (A.length)) || (col < (A[row].length-1)) ) ) { if (col < (A[row].length-1)) col++; else { row++; col = 0; } } //Postcondition: If A[row][col] isn’t ‘17’, no component is if (A[row][col] != 17) System.out.println(“No value equaled 17.”); else System.out.println(“Found it!”);

  46. What’s wrong with the following? boolean found = false; for (int current = 0; current < sequence.length; current++) { found = (sequence[current] == 3); } if (found) System.out.println(“Found it.”);

  47. What’s wrong with the following? boolean found = false; for (int current = 0; current < sequence.length; current++) { found = (sequence[current] == 3); } if (found) System.out.println(“Found it.”); Answer: found can be made true and false by one array component after another; we want it to stay true once it’s become true

  48. What’s wrong with the following? boolean found = false; for (int current = 0; current < sequence.length; current++) { found = (sequence[current] == 3); } if (found) System.out.println(“Found it.”); Answer: Found can be made true and false by one array component after another; we want it to stay true once it’s become true: boolean found = false; for (int current = 0; current < sequence.length; current++) { if (sequence[current] == 3) found = true; } if (found) System.out.println(“Found it.”);

  49. Data Bounds • Data bounds are useful for divide and conquer problem-solving methods • describe sections of the array in terms of relative borders (rather than fixed subscripts or stored data values) • divide a large array into smaller pieces that can be dealt with separately • place barriers between ‘useful’ information and ‘irrelevant’ information • gradually shrink the unexplored portion of an array until it holds the answer or is empty

  50. Data Bounds limit thesolution space • Data bounds are usually set with subscript variables that serve as pointers to the portion of the array that we’re interested in • They limit the solution space by minimizing the array’s unknown area

More Related