1 / 14

Oct 6-7

Oct 6-7. loops revisited I/O arrays. Loops: #1. Write a program to calculate and print the average of all the multiples of 3 from 3 up to (and including) 33333. Invariant: s contains 3 + 6 + 9 + ... + i and i is a multiple of 3

lenora
Télécharger la présentation

Oct 6-7

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. Oct 6-7 loops revisited I/O arrays

  2. Loops: #1 Write a program to calculate and print the average of all the multiples of 3 from 3 up to (and including) 33333. Invariant: s contains 3 + 6 + 9 + ... + i and i is a multiple of 3 c is the number of values that have been summed in s Initalization: i= 3; s= 3; c= 1; Stopping condition: when i = 33333 So, continue while i != 33333 Body: make progress i= i+3; maintain invariant s= s+i; c= c+1;

  3. public static void main (String[] args) { int i= 3; int s= 3; int c= 1; // invariant: ... while (i != 33333) { i= i+3; s= s+i; c= c+1; } System.out.println("average = " + s/c); }

  4. Loops: #2 Read in a sequence of positive integers (followed by a 0) and print the biggest together with its frequency of occurrence. Invariant: x the last number read max the largest value read in so far freq the number of times max has appeared

  5. Basic input class import java.io.*; publicstaticvoid main (String args[]) { int a; // initialize TokenReader object in to read // from standard input. TokenReader in = new TokenReader(System.in); // Read one number into a System.out.print("Please enter an integer: "); System.out.flush( ); a = in.readInt( ); System.out.println(“a: ’’ + a); }

  6. Some input methods // read and return a value of type int public int readInt( ) // read and return a value of type double public double readDouble( ) // read and return a value of class String public String readString( ) // Skip the rest of the input line and return as a string // all the characters on the next line public String readLine( )

  7. import java.io.*; publicstaticvoid main (String args[]) { // initialize TokenReader object in to read from standard input. TokenReader in = new TokenReader(System.in); int max = 0; //maximum integer read in so far int freq = 0; //frequency of max // read in integers until a 0 int x = in.readInt(); while (x != 0) { if (x > max) { //x is a new max value max = x; freq = 1; } else if (x == max) //x is the same as the current max value freq = freq + 1; x = in.readInt(); //read in next value from standard input } }

  8. Array Rules • When an array is allocated int[ ] A = new int[size]; size may be any integer expression. • When using A[exp] to refer to an element, the subscript exp may be any integer expression. • The elements in an array are numbered A[0], A[1], …, A[size-1], where size is the number of elements in the array. • In a reference to an array element A[exp], it is an error if exp<0 or exp=size. • Be sure to be careful to distinguish the subscript (or location) of an array element from the data that is actually stored in that location.

  9. Arrays: #1 • Write a program that takes an array x[] of double's (assume that it is already initialized) and create a new array s of the same length such that s[i] is the average of x[i] and its circular neighbors: • For j in the range 0 <= j < x.length-1, we say x[j+1] is the neighbor to the right of x[j]. • For j in the range 0 < j <= x.length-1, we say x[j-1] is the neighbor to the left of x[j]. • We say x[0] is the neighbor to the right of x[x.length-1], and x[x.length-1] is the neighbor to the right of x[0]. (This is the circular part of "circular neighbors": think of joining the ends of x[] together, forming a circle, making the original ends into neighbors.) • For example, here are some values for x and the corresponding outcomes s: • x = [] --> s = [] • x = [2] --> s = [2] since (2+2+2)/3 = 2 • x = [0 9] --> s = [6 3] since (9+0+9)/3 = 6 and (0+9+0)/3 = 3

  10. … //code here initializes x int n = x.length; double[] s = new double[n]; int i = 0; // invariant: 0 <= i <= n = x.length, // s[0..i-1] has been computed, // and s[i..n-1] remains to be done while (i < n) { int left = i-1; int right = i+1; if (left < 0) left = n-1; if (right == n) right = 0; s[i] = (x[left] + x[i] + x[right]) / 3.0; i = i+1; } ...

  11. … // code here initializes x int n = x.length(); double[] s = new double[n]; int i = 0; // invariant: 0 <= i <= n = x.length, // s[0..i-1] has been computed, // and s[i..n-1] remains to be done while (i < n) { s[i] = (x[(i-1+n) % n] + x[i] + x[(i+1) % n]) / 3.0; i = i+1; } … This solution uses the remainder operation % to “wrap” values. We use (i-1+n) % n instead of just (i-1) % n to be safe: in Java, % can/will return negative values if given negative dividends.

  12. Arrays: #2 // Move top card k[0] down into position j, // thereby pushing cards k[1..j] into positions 0..j-1 public static void cycleTopDown(int[] k, int j) { int top = k[0]; int i = 0; // invariant: 0 <= i <= j, and k[1..i] has been moved to k[0..i-1] while (i < j) { k[i] = k[i+1]; i = i+1; } k[j] = top; } // Create an array k[] and // repeatedly cycle k[0] down into position k[0] until k[0] is 0 public static void topCycles () { int[] k = {2, 4, 3, 1, 0}; // Repeatedly cycle k[0] into position k[0] until k[0] is 0 while (k[0] != 0) cycleTopDown(k, k[0]); }

  13. Carefully trace a call to topCycles(): a) Show EVERY step -- ALL of them -- until one iteration of the loop in topCycles has completed. Remember to trace execution of the statements within method calls. You will have to draw diagrams showing the state of affairs at about 10 places. Do not worry about where to place a frame for a method-call. Place all frames outside of all other boxes. b) Show us the contents of k[] after each iteration of the loop in topCycles (there are at most 7 iterations).

  14. Solution (w/o the trace) Here are the contents of k after each iteration of the loop in topCycles (we include the contents before entering the loop): 0 1 2 3 4 <- positions - - - - - 2 4 3 1 0 <- contents 4 3 2 1 0 3 2 1 0 4 2 1 0 3 4 1 0 2 3 4 0 1 2 3 4

More Related