Homework Solution

Arrays

Problems to be Submitted (30 points)

  1. (10 points)

    Assume that variable data represents an array of floating-point numbers. Provide a segment of Processing code that reassigns each entry of the array to be double its current value.

    for (int j=0; j < data.length; j++) {
      data[j] = 2 * data[j];
    }

  2. (10 points)

    The Processing library includes a function max() that returns the maximum value in an array. It would support a calling syntax such as

          float biggest = max(data);  // assuming data is an array of floats
    Of course, if that function did not exist, we could program such a function ourselves. Please give a self-contained implementation of a function named max that takes a nonempty array of floating-point numbers as a parameter, and which returns that maximum floating-point value that can be found in the array.

    float max(float[] data) {
      float answer = data[0];   // biggest we've seen thus far
      for (int j=0; j < data.length; j++) {
        if (data[j] > answer) {
          answer = data[j];          // data[j] is new "biggest" thus far
        }
      }
      return answer;
    }

  3. (10 points)

    The following program moves a randomly located and randomly colored square in a "southeast" direction, wrapping at the boundaries. Rewrite the program, using arrays to do the same for 50 squares with randomly chosen initial positions and colors.

         int x;
         int y;
         color c;
          
         void setup() {
           size(500, 500);
           x = int( random(width) );
           y = int( random(height) );
           c = color( random(255), random(255), random(255) );
         }
    
         void draw() {
           background(255);
           x = (x + 1) % width;
           y = (y + 1) % height;
           fill( c );
           rect(x, y, 20, 20);
         }
    


Last modified: Friday, 27 February 2015