Homework Solution

Control Structures

Problems to be Submitted (30 points)

  1. (6 points)

    Given the following definitions, what value and type do the following expressions evaluate to?

    int a = 2;
    int b = 5;
    float x = 2.0;      
    float y = 10.0;
    
    1) y * (b - a)
    float with value 30.0
    Note that this is evaluated as 10.0 * (5 - 2), which is 10.0 * (3), which is then the floating-point value 30.0.


    2) 10 % b + x
    float with value 2.0
    Note that this is evaluated as (10 % 5) + 2.0, which is 0 + 2.0, which is then the floating-point value 2.0.

    3) b / a * x
    float with value 4.0
    Note that this is evaluated as (5 / 2) * 2.0, which is (2) * 2.0 since the integer division 5/2 results in 2. Finally, we have (2) * 2.0 which results in the floating-point value 4.0.

  2. (6 points)

    Translate the following while loop to an equivalent for loop:

    int n = 0;
    while (n < 50) {
      ellipse(n, n, 2*n, 2*n);
      n = n + 10;
    }      
    

    for (int n=0; n < 50; n = n + 10) {
      ellipse(n, n, 2*n, 2*n);
    }

  3. (9 points)

    Write statements that will change the background of the canvas to a random color if the current mouseX and mouseY are near the bottom left corner of the sketch window, and do nothing otherwise. (Hint: you can monitor the mouseX and mouseY variables from within draw, or use the mouseMoved() function, which is called whenver the mouse is moved over the canvas. That function provides both mouseX and mouseY as well as previous values pmouseX and pmouseY.)

  4. (9 points)

    Write a script that paints a grid over the canvas using horizontal and vertical lines. The resolution of the grid (i.e., the number of cells in each direction) should be determined by two int variables, r and c, where r specifies the number of rows and c specifies the number of columns.


Last modified: Friday, 27 February 2015