CSC 161 Grinnell College Spring, 2012
 
Imperative Problem Solving and Data Structures
 
 

Laboratory Exercise Structuring Structs

Structs

C groups variables together using structs. Using a struct, you can simplify parameters, organize data, and protect information. Now let's explore some basic uses of structures.

Simple Structs

  1. Declare a simple Point struct which contains an int x and int y int coordinate. What scope (where it has to be declared) will you want this structure to be in if you plan on using it in main() and your other functions?

Setting a Pixel

  1. Create a file named structs.c in your directory for this lab and set it up in the standard way. Save the blank white picture, blank.jpg, into your directory, load it into your program with the rLoadPicture() function and save it as a Picture * variable. Note: You don't have to connect to the robot to do this.

  2. Look at the declaration of the Pixel structure in section 3 of MyroC.h.

    1. Declare a black Pixel (rgb of 0, 0, 0).

    2. Why are you able to declare your struct as just a Pixel as opposed to a struct Pixel?

      Hint: Look over typedef from the reading

  3. Draw a black pixel in the middle of the picture using rSetPicturePixel() and then show the modified picture.

Using Your Point

  1. Write a function void drawPoint (Picture * pic, struct Point p, Pixel pix) which will draw a pixel onto the Picture at the given Point. Then draw your black pixel again somewhere on the Picture.

Drawing a Rectangle

  1. Before drawing a rectangle, it would be convenient to be able to use our Point without having to explicitly say struct. Change your struct Point declaration so it is in the following format:

     typedef struct {
         variables
    } Point;
    

    This defines a new data type for you to use freely within your program.

  2. Now declare a rectangle structure using this new type! You can freely nest structs within structs, so make a Rect struct which contains four Point structs. (you can also make Rect contain a four element Point array, if you want to be really fancy).

  3. Write the function drawRectangle (Rect r) which will draw a rectangle on your picture (just the outline, you don't have to fill the rectangle in). It may help to make the precondition of your function that the points in your rectangle are in a particular order (e.g. top left, bottom left, bottom right, top right).

  4. Test your function with various Rects to make sure it works.

  5. Now make your rectangle have bolder lines so that it is more distinct.

Feedback Welcome

Development of laboratory exercises is an interative process. Prof. Walker welcomes your feedback! Feel free to talk to him during class or stop by his office.