CSC 161 Grinnell College Fall, 2011 Imperative Problem Solving and Data Structures

# Laboratory Exercise Structuring Structs

## Structs

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

### 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 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?

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

### Declaring a Point

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

2. 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. 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.

## Reminder: Complete Evaluation Form

When you have finished this lab, be sure to fill out its evaluation form in the "Lab Evaluation" section for CSC 161 on Pioneer Web.