You are on page 1of 32
Chapter 1 Libraries and Interfaces: A simple Graphics Library Art it seems to me, should simplify. That, indeed, is very nearly the whole ofthe higher artistic process; finding what conventions of from and what details one can do without and yet preserve the spirit ofthe whole. — Willa Cather, On the Art of Fiction, 1920 OBJECTIVES @ Tounderstand the meaning of the terms interface, package, abstraction, implementor, end client as they apply to libraries To recognize thet intefaces are represented in C using header files oe To be able to read the srahicsh interface, which provides access to e library for deowing simple pictures on the screen, and to understend the conceptual abstraction used by the graphics library. @ Toleamn haw to draw lines using Movesen and Danline and to draw arcs using DrawArc @ To lear how to extend the besic capebilities of the graphics librery by defining new higher-level functions, @ Topractice writing large programsusing the grephics peckege @ To appreciate the importance of general tools and the essociated strategy of bottom- vp implementation. Every program you have seen or written in this text has called at least one Library function Even the one-line program helo.c calls pati to display its message on the screen In modem progemming it is impossible to write interesting programs without calling librery functions, and by this point, you should be reasonably adept at calling them. Sofay, the functions you have written have all been part of @ single program. You can call them from the main program or from other functions thet are pest of the seme program file, but you have not been ably to take your own functions and put them into @ library thet ‘you cen then use for any number of later programs. Before you cen do so, you need to lean more about what @ librery is and how it works. Enormous power comes fram being ble to design good libraries end use them well A key part of thet power comes fram understanding the concept of en siferface, which is the main topic not only of this chepter but of the next several chapters as well To give you a sense of what en interface is end how it works this chapter concentrates on having you read through en existing interface rether then heving you Gesign one from scretch Before attempting to write novels, authors usually spend many ‘years reading them. In doing so, they lear about the form of the novel and develop their own appreciation of what makes @ particular novel good. Here, your job is to learn the basic structure of interfaces, and the best way to do thet is to study existing examples. You ‘will have the chance to write your own interfaces beginning in Chapter 8 ‘This chapter begins by outlining the conceptual structure of interfeces and defining several terms thet make it easier to tek ebout them. It then introduces a simple graphics brary thet enables you to draw pictures on the screen Thet library will make it possible for you to wsite programs that are much more exciting then those you have seen in the preceding chepters, which makes the graphics ibrery interesting in its own right. As you ‘use the graphics library, however, it’s important to keep in mind such issues as how libravies work, whetthey contain, and how interfaces are used to describe them 1-1The concept of an interface In English, the ward interface means a common boundary between two distinct entities. The surface of a pond, for exemple, is the interface between the water and the air Inprogremming en interface constitutes « conceptual boundary rether then a physical one an interface is the boundary between the implementation of « librery and progems thet ‘use that library. Information passes across thet boundary whenever functions in thet library. we called, The interface mediates and gives structure to the exchange of information between the library and its users Conceptuelly, a programming interface also represents @ shared understending ebout the nature of thet boundary, providing both crestors and users of a library with the critical information they need to know. Consider, for exemple, the meth library introduced in Chapter 5. The math librery defines several functions, such es owt. Programs thet sue the math library can call sqt to calculate @ square root without having to specify the actual steps involved. Those steps are pat of the implementation of the square root function, which was written by the programmers who created the math library itself. Chapter 6 presented tro possible strategies—Newton's method end Taylor series expansion—far implementing the sat function The library implementors might have sued one of those strategies or any other ‘algorithm thet computes the correct result Knowing how to call the set function and knowing how to implement it ere both important skills. It is critical to realize, however, thet those bro skills—calling @ function ‘and implementing one—are to a lenge extent unrelated Successful programmers often tse functions thet they wouldn't know how to write, Conversely, programmers who implement «library function cannot anticipate all the potential uses far that function To emphasize the difference in perspective between programmers who implement @ library and those who use it, computer scientists have edopted specific terms to refer to programmers working in each of these capacities. Naturally enough, programmer who implements @ library is celled an implementer. Because the word 1er means someone who runs a program rether then someone who writes pert of one, a programmer who calls functions provided by a library is called « eliemt of that library? * Incomputer science, the ten client sometines eft to code that uses baxy ad sometimes to the programmer who wnites that code. If thexe isa possiblity for confusion, I wil refer to code tt sues@ [brary escent code ltiough I wal also follow the standard convention and use chent in such case, as Jong asthe intents clear Even though clients end implementors have different perspectives on the library, both, must understand certain aspects of that Library's design. As a client, you don't need to mow the details of its operation, but you do need to know exactly how to call it. As an. implementor, on the other hand, you ere not directly make it possible for them to do so by ‘providing the information they need to call the functions it contains. For each function in the library, the client must know the following, m Itsname The ergumentsit requires and the types of those arguments The type of result it returns ‘That this information is precisely what « function prototype provides is by no means @ coincidence. In C, the prototype for a function and its implementation ere seperated because they convey information to different audiences, The client end the implementor must agree on the function prototype, which means that it is past of the interface. By contrast, only the implementor is concerned with the function implementation The act of making «function evaleble to clients by including its prototype in the interface is called eaporting that function, ‘The relationship between the client end implementor is illustrated in the following, ogram client Interface Implementation Responsible for Both sides agree on: Responsible for: (@ how a function is (@ the function © how a function used prototype wak Interfaces and header files In computer science, an interface is a conceptual entity. It consists of an understanding between the programmer who implements @ library and the programmer standing between the programmer who implements a ibrary and the programmer who uses it, spelling out the information thet is required by both sides. When you write aC program, however, you must have some way to represent the conceptual interface as part of the actual program. In C, an interface is traditionally represented by a header file. You have warked with header files ever since Chapter 2 and have encountered several different ones, including siéoh, mathh, and gerbh. Each of these header files specifies the interface to the ‘underlying library. ‘The distinction between the abstract concept of an interface and the actual header file thet represents it may seem subtle at first. In many ways the distinction is the same as thet betveen en algorithm and a program thet implements it. The algorithm is an abstract strategy, the program is the concrete realization of thet algorithm. Similarly, C uses header files to provide a concrete reslization of an interface. ‘The same distinction between a general concept end its programming manifestation also comes up in the definition of two other terms thet are often used in discussions of interfaces. In computer science, you will often hear the term package used to describe the software that defines a library. If you were assigned to develop a lbrery, past of your job would consist of producinga h file to serve as the library interface and one or more « files that together provide an implementation. Those files constitute the package To get « full understanding of a library, how ever, you must look beyond the software Libraries embody ‘specific conceptual epproach thet transcends the package itself. The conceptual basis of « librery is celled an abstraction ‘The relationship between an abstraction and a packege is best illustrated by an example. When you write your programs, you use the printf function in the svioh interface fox all output operetions. For input, you use functions like Geihieger, GetReal, and Gerline, which are made aveilable through the simpioh interface. The siioh interface provides functions for accepting user input, but they turn out to be more difficult for beginning programmers to use. The two libraries embody different approaches to input operation: the stloh interface emphasizes power end flexibility while the sinpoh interface emphasizes simplicity of structure and ease of use. The epproach used in each of these interfaces is part of the abstraction The associated packages implement those abstractions and make them seal in the sense thet they canthen be used by programmers. ‘The contents of header files are discussedin detail in Chapter 8. The best way to get a general impression of how header files are sued to represent an interface, however, is to look at an example. The following section welks you through the goshicsh header fil, which specifies the interface to a simple abstraction for drawing pictures on the screen 1-2.An introduction to the graphics library Compared with computer games or commercial wardprocessing systems, the progres you have worked with so fer seem relatively tame, Until nov, all programs in this text have displayed their output on the computer screen as mumbers and strings formatted by the pint! function Modern computer programs typically use the screen in @ much more creative way thet involves pictures and fancy graphical displays—features thet make using the computer both easier and more exciting. Although graphical displays may make life easier for the user, incorporating them into a program usually makes life mare difficult for the programmer. Considered in its entirety, generating even a simple line drawing on the screen is en enormously complex programming problem—well beyond the scope of this text. Luckily, there is no need to look at the problem in its entirety. If you have access to a graphics brary, you can ignore the underlying complexity and concentrate instead on high-level operations thet cause lines and other graphical features to appear on the screen. The details are hidden on the implementation side of the interface boundary. To use the graphics library, you must specify its interface by writing the appropriate ‘nce line at the top of your program, which in this case is incude “graphics h The underlying model for graphics. Before you can appreciate the procedures and functions available in the gshicsh interface, you first need to understand the underlying abstraction. How do you specify positions on the screen? What units should you use for length? These questions are important for understanding the grephical model, which is a central part of the conceptual abstraction, ‘The graphical capabilities of the display screen you ere using depend on the computing harchware you have available. The srshicsh interface was designed to be as general as possible, and this generality makes it difficult to describe precisely how the gephical display will be presented on any given system. Typically, when you start up the gephics package, a new rectangular window celled the graphics window is crested on the soreen and used as the drawing suface. Whenever you cell procedures and functions in the gephics library, the results are displayed in the graphics window. To specify points within the graphics window's the graphics library uses an approach. that should be familiar from high-school geometry or algebra. All drawing in the graphics window takes place on @ conceptual grid as illustrated in Figure 7-1. As in traditional geometry, points ere identified by specifying their position relative to the exigin, which is the point at the lower left corner of the graphics window. The harizontal and vertical lines that emanate from the origin along the edges of the graphics window are called the axes, the xvas runs along the bottom of the window and the J-cv#s runs up the left side. Every point within the graphics window is identified by a pair of values, usually written as (1), that specifies the position of that point along the r and,y axes. These values are called the 3 TTT TTT 0 1 2 3 coordinates of the point Coordinates are measured in inches relative to the arigin, which is the point (0,0). Form there, x values increase as you move to the right, and y values ‘increase as you move up TESTU continatesin the gepbiceitemy Coordinates in the grephics library come in two forms: © Absolute ceordinates specify a point in the window by giving its coordinates, absolute coordinates (2.0, 1.5). © Relative coordinates specify a position in the window by indicating how fer thet point is along each exis fram the last position specified. For example, the open. dot in Figure 7-1 has absolute coordinates 2.5, 1.5). If, however, you express its coordinates reletive to the solid dot, this point is shifted by the relative coordinates (0.5, 00). If you wanted to connect these dots with a line, the standard approach would be to specify the first point in absolute coordinates, but then to specify the connecting line in the relative mode, ‘The best mental model to use for the drawing process is to think of « pen positioned over a piece of transparent graph paper covering the screen You can move the pen to any location on the screen by specifying the absolute coordinates. Once there, you can draw a streight line by moving the pen relative to its current location with the pen continuously touching, the graph paper. From there, you cen draw enother line beginning fran where the lest one ended ‘The functions in the graphics.h interface ‘The orahiceh interface exports only a small number of functions and procedures for ckawing To draw complicated pictures, you would certainly went more capabilities, but the simplicity of this interface makes it possible to present the entire graphics package in cone chapter. You can easily understand it all. The graphics library contains the following functions: bite opics) Initializes the graphics package MovePen (x, yi ‘Moves the pento an absolute position Drawline (ee, dy) Draws a line using relative coordinates DrowAe(s, tert, sw eep] Draws an arc specified by a radius andtwo angles Geto Returns the width of the grephics window GetiindowsHeiht Returns the height of the graphics window GetCurentk Returns the current x-coordinate of the pen. GetCurestY 0 Returns the current y-coordinate of the pen. ‘These functions provide the capabilities you need to begin drawing simple pictures in the gaphics window. To understand how to use them, however, you need to read the documentation for each, which is provided by the interface 1 My fens who exe artis tell thet they tendto think of figure ike /\/ teasing ie, bce iti ble In i tet we il hye ee ‘mean a segment of staight ine, Thus, the figure i the preceding diagram is actually composed of thee lines connected end to end ‘The interface for the graphics library is contained in the header file gaphiceh, shownin Figure 7-2. The header file runs on for severel pages, and i is important thet you not try to ‘understand it thoroughly all at once. You cen sead through the initial comments end peruse the file to get a sense of its structure, butit is usually best to use the interface mainly as a reference guide. As new functions are introduced in the text, you should look up the corresponding entries in the interface to see if they make sense VQ CCA 0 2 AZ oraphics.h interface “Tis ieterface provides access t a simalelibary of “functions that make itpossble fo draw ines and arcs * onthe screen. This interface presents a portable * aberacton tat canbe used witha vanity of window * sytem implemented on dferenthardware platforms. " finde _graphiosh ‘tiene grants * The Wray provides several functions droning Snes * and cecular arcs in a region ofthe screen that is * defined as the “apics window * Once dawn, these “Ine and arcs sy in ther positon, whchimeans that “the package can only be used fr static pictures and rot “er amatton “individual points within the window are specied by ving their x and ycoordintes. These coordnates are * real numbers measured in nches, wih he orgin ithe “loner eft comer, a isin tdi tonal mathemati. * The cals avail inte package are sted below. More * complete descrton are included with each function * desertion * itaphies 0; MovePen i ¥; Dranline (x,y; + DrawAref, str, sweep); * width = Getlindow Width 0; * height = GettindonHeight 0; + x=GetCurent 0; + y=GetCurentY 0; * Funeton: bitGrashice * Usage itGeaphcs 0; “This procedure creates the graphics window onthe screen, “The cal to lriGraphics must precede any calls to other “functions inthis package and must also precede any pitt * euput. nmast cases, the IntGreshice call the feet * calementin the fnetion man " eid leitGraphis (vid; P * Funeton: MovePen * Usage: MovePen, “The procedure maves the curent point othe positon * fy) without drawing ane. The model is that of “be pen being Ited off he graphics window eurace and then moved tis new positon " wid MovePenfe, P Funeton: Dawline sage: Draline (x,y); “The procedure dawe ane exeding fom te curent * gint by moving he pen dxinches inthe x rection * and dy inches inthe ysirecton. The fia positon “becomes the new eurent point, " eid Dranline (double dx, double dy); P * Funeton: Dawe * Usage: Drew F, stat, sweep; “Tis procedure daws a circular ar, which ava * athe curent point. The ac tslf aks radius, and ‘sare atthe angle epecifed by he parameter stat, “relat the center ofthe cil. This angle ic * measured in degrees counterclockwise fom the 3 o'ock * goston along the x-axis, a in tedtinal mathematics. * Forexampl, i sarti 0, he ae egine atteh 3 o'lock * poston; startie 90, te are begin at he 12leck * positon; ard soon. The Facton of the cil dawn is * specifed bythe parameter sweep, which i leo measwed in * degrees. F sweeps 360, Daw draws a complete cece; * sweep is 9, teraws @ quarter of» ciel. the value of smeep is psitve fhe aris drawn counterclockwise fom “the curentoint Hf sweep isnegatve, he arc is dann * locknise fom the curent point The curent pont atthe * end ofthe DrawAe operation ste fal positon of he pen * along the ar. * Brame: + DrawAr 0,360) Draws a circle toe let ofthe curent point * DrawwAre (8D, 180) Draws the let half ofa semicircle staring from the 12 o'clock pasion * DrawArc 0,80) Draws a quarter cele tom the 3 o'clock n he 12 o'clock sion DrawAr 0, $0) Draws a quarter cle fam the 3o‘lock he 6 o'clock positon * DrawAr 80, 80) Draws a quarter ccle tom the & o'clock the 8 o'clock positon. 4" wid DrawAre (lube r, double er, dole sweep); P * Funcion: GetWndonWalh, Getindon Height * Usage: ith = GetlindaniNid te; + Ieiht = Getiindow Height 0; ‘These functions return the with and height ofthe srapice * wind, in inches. " double GeiWindon With (08); double GeiWiedowHesht (vod, P Funeton: GetCurentX, GetCumentY Usage: x= GetCurentX 0; “These Anctone return the curent x and ypostns " double GetCurentX (vid ouble GetCurentY (vo Hen ‘The orapiceh interface contains a few stylized lines that ere part of every interface ‘After the intiel comments are the lines ‘hindet _graphics_h ‘ene _oraphies_h ‘The very lest ine in the interface is tend ‘The purpose of these lines is discussed in Chapter 8, which explains how to write an interface. For the moment, how ever, you can ignore these lines. Although they tum out to be important to the compiles, they are not et all important to you understending of how the interface works, ‘The remainder of the interface consisits only of comments and function prototypes Of these, the comments account far more that 90 percent of the header file. Even though the compiler ignores the comments they are in many ways the most important part of the interface. The real audience for the interface is not the compiler but the programmer who is trying to write client code. The purpose of the comments is to help programmers ‘understand the abstraction as a whole and use the facilities provided by the interface. Initializing the package ‘The first procedure in the gaphicsh interface is lniGrashics. As the comments in the interface indicate, this procedure initializes the graphics library and must be called before ‘any other function in eh package and before print! is used to display eny output on the screen It is commonfar @ library package to require some initialization. When you use an interface, it is a good policy toed through it to see if it requires any initializing operations Drawing straight lines ‘The function MovePen and Drawlne are the principal line-drawing tools the graphics brary offers As a first illustration, let’s draw a single straight line thet extends one inch ‘upward ram the point (0.5, 0.5). The first step in any main program thet uses the graphics ‘COMMON PITFALLS. Make sure the fst line in any programthat uses the graphics library isa call ‘he function IitGraphics ‘As a more general rue, you should remember that lbvaries of en need initaizaton of some sot. You should therefore check each interface t see wheher any iitalizaton is required brary is abways britGraies 0; To deaw the line, you start by moving the pen to the point @.5, 0.5) MovePen (05, 10); From there, all you have to do is draw a line in which the 1-coordinate does not change at all andthe J-coordinate moves one inch up the screen: Drawtine (00, 10); ‘The complete program is shown in Figure 7-3 onelines i Fie: onelne “The program draws a single aight ne 1 ‘fnclude ‘oclude “gen h* ‘clude “grenhics h” maint) © titGraphies 0; MovePen 15, 0.5); Drawline (0.0, 1.0); ) Rumning the program draws the following picture in the graphics window Ifyou wentto draw a square instead of a straight line, you can simple add three more calls toDawline to the program, so thet the main program looks like this: maint) IritGraphics 0; MovePen 015, 0.5), Drawline 0; 10) Drawline (10, 0.0) Drawline (0; -1.0); Drawline (1.0, 0.0); ) which renults in picture Note that each line begins where the last line ended, This behavior is consistent with the conceptual abstraction of pen moving around on the sutface of the graphics window. Drawing circles and arcs ‘The only other drawing function the graphics library provides is Drwhre, which you ‘use to create an arc consisting of some fraction of a circle, The proto type for Dawe is vid DrawAre (double r, double start, double sweep); Unlike many of the procedure prototypes you have encountered so fer, however, the ‘prototype alone is not sufficient for you to understend exactly what this function does. For a complete understanding, you need to look at the commentsin the interface as well, which appeer in Figure 7-4 Interface entry for Draw Are r * Fane: Draw 1 Usage: Draws (start, sweep); J procedure draws a circular ar, which always eine he curentoint The ac self has rus, and * carts atthe anle specifed bythe parameter stat, “relative the center of cil. Thi ange ie * measured in degrees counterclockwise fom the 3 o'clock * positon along the aaxis, as intra tonal mathema ics “For example, # static 0, be ac begns athe 3 o'clock * positon; if startis 9, the arc begins a the 12 o'clock * positon, and so on. The faction ofthe cicle dawn is * specied by te parameter sweep, which is also measured in * degrees. sweep i 360, DrwArcdrams a complete cite; “sweep is 0, eran a quarter ofa circle. Fe value * cf eweep ic postive, the arc ie drawn counterclockwise fom “the curent pont. F sweep isnegatve he ar is dawn * clockniseform the curent pot. The curentpeint atthe * end of he DrawAre operation isthe fal positon ofthe pen * along he ar * Examples + DrawAre f 0, 360) Draws acc tthe let of he curent point DrawAre F 90, 180) Draws he let half ofa semicircle start fom the 12 oock positon + DrawArcf 0, $80) Draws. a quarter cle fom the 3 o'clock t the 12 o'clock positon + DrawAref 0,80) Draws a quarter circle fom the 3 oock to the 6 o clack positon + DrawAref, £0, 80) Draws a quarter circle fom the & o'clock to he §o clack positon wid DrawAe ubler, double start, double sweep); ‘The first sentence in the comments for Draw/e reveals an importent piece of information: the arc begins at the current position of the pen. This fact means you have to call MovePen to position the pen at the beginning of the arc you wish to draw, just es you do when you begin drawing a line. The comments also give critically important information about whetthe angels mean and how they ere measured As a client, you need to know this information to use the function successfully. The comments end by offering five examples thet ilustrate the use of Daw. Such examples can e extremely helpful because itis almost abv ays easier ot call @ function whenyou have en exemple touse as « model Here, for instance, the documentation suggests that you should be able to draw a complete circle to the left of the current point by using the call DrawAre 0, 360); ‘The arc has radius r and begins at the angle represented by 0 degrees, which is the 3 o'clock position It extends for 260 degrees, thus creating a complete circle. The starting ‘position on the arc is the cwrent position of the pen when the call is made, Relative to the circle that is dravn, this position is the rightmostpoint, andthe entire circle lies to the left Based on this discussion, you should easily be able to write a program thet draws a circle with a half-inch radkus, centered at the point (I,1). All you have to do is move the pen. to the starting point at the sight edge of the circle and then can DrawArc, The main ‘program is maint) { initGraphies MovePen (5,10) DrawAre (15,0, 360); ) which produces the following display: To get more of a feeling far how Dawhre warks, you can try the other examples given in the documentation For exemple, replacing the DnwArc call in the program by the statement DrawAre ‘05,0, 180); ‘produces this figure: Obtaining information about the graphics window ‘The lest four functions exported by the srphicsh interface do not actually affect the graphics window but instead return information about it. The fmetions GetlindowiVidthe and. GetiindowHeight return the dimensions of the grephics window, measured in inches. For exemple, using the statements MovePen 0, 0); Dranline (GeiindowWidh (, GetWindow Heh 0); sesutls in a diagonal line the extends across the entire graphics window. ‘These functions also enable you can use to center a drawing The 1-coordinate of the center is half of the screen width end the -coordinste is helf of the screen height. You can therefore move the pen to the center of the screen by using the statement MovePen (GetWindon Width ()/2, GetWindowteight (2); ‘The function GeCurentX and GetCumentY return the x and j-coordinates of the current pen position These functions ere used primarily in writing higher-level functions and are discussed further in the section on “Switching between absolute and relative coordinates” Iter in this chepter 1-3Building your own tools ‘The tools introduced in the last section are more useful than you might at first realize. Not only do you have some experience in drawing lines and arcs, you also have begun to ‘put those tools together into program fragments thet perform more sophisticated functions. For example, you lesrned how to put four lines together to make a rectangular bor and how touse the DawAe function tomake complete circles. But because drawing bores and circles are common operations, it would be tedious if you hed to go through all the steps involved far each bor ar circle you wantedto draw. It would be more convenient if the designers of the library hed simply given you additional tools for drawing boxes and circles. However, whether such functions are explicitly pert of the gapiceh interface doesn’t actually matter. Because C gives you the ebility to define your own functions, you can create these tools yourself. Defining DrawBox Todhustate this rocess, suppose you wantto define a procechire Danlox thet draws a rectangle oriented along the coordinate axes. The first step in the process of writing DawBox is to define its prototype. Doing so is an exercise in design. You know the name of the procedure, but you also have to think about what arguments to inchude. A useful strategy for figuring out whet arguments are required is simply to ask yourself whet information the ‘implementation needs. You cen't just give it the progremming equivalent of the English command.” Draw a sectengle.” The implementation needs to know how big a rectangle snl where to put it on the screen The traditional way for the implementation to get this information is to have the client supply it in the form of arguments Even so, there is more than one way to design the DrawBox procedure. One possible design for DanBox would be to use only two arguments —sidh end heght—to specify the cimensions of the box. To indicate the position of the bar you would cell MovePen, after which the bax would be drawnselative to that position Thus to draw a bax at position (c, you wauld write MovePents, Ww ‘This example is not the final design. Drea i, eh; Another alternative would be to design DrawSox to take four arguments—x, y, width, and hsisht—thereby combining the act of setting the position and thet of setting the dimensions, as follows: DrawBox ey with, hight, Because the second form is usually more convenient for the caller, it probably makes more sense to adopt the second approach, but either design wauld certainly wark. In addition to determining how many arguments ere requited, you must also specify the interpretation of the first two arguments What does it mean to draw @ point (% y)? A bor does not have an obvious starting point. Where is the point (&, y) relative to the sectangle? One possibility thet is convenient for some applicetions is to implement DranBox so thet the point (K \) specifies the center of the box. A more traditional strategy, how ever, is to define the origin of the box to be its lower left comer, just as the lower left comer of the graphics window is the origin of the entire coordinate system. The point (« \) then indicates the position of the origin No matter how you choose to define the position (\, \) in relation to the box, the main thing you need to do is make sure thet the documentation for the function mekes your design decision clear ‘Thus one possibility for the DawBox prototype is wid Drawibox Wouble x, double y, double width, double height); where and y specify the origin of the box and with and height specify its dimensions. Since this procedure is one of your creations and not part of a library, you need to define the implementation as well. The implementation consists simple of the steps necessary to draw the four lines of the figure, expressed in terms of the parameter values. You have elready ckawn one box in this chapter; all you need to donow is convert the explicit coordinates to the more general, parameter-based form wid Drawiox double, double y, double with, double height { MovePen x,y; Draline 0, height) Drawline (ith, 0); Drawline 0, wet); Drawline (with, 0) ) ‘The implementation moves to the origin point for the bor and then draws the four line segments necessary to complete the bor. Now thet you have this procedure, you can chenge the implementation of the program to draw a box on the screen so thet it uses your new tool. The resulting program, davkox.c, appears in Figure 7-5 (QO TREE drawbex.c incde ) CO Make certain that your function behaves in a reasonable way if the height or width is less then ComerRadus 6. Write « program to draw your initials on the graphics window. For exemple, if I wrote this program, I would want the output tobe You'll need to think ebout the best decomposition to use in writing the program. Imagine that you've been asked to design a more general letter-drawing library. How ‘would you went the functions in thet library to behave in order to make using them as simple as possible for your clients? 7. White @ program thet draws a picture of the Hellow een pumpkin shown in the following VV A diagram. ‘As in the howe program shown in Figure 7-7, your picture should be controlled by several constants: tiene HeadRadus 1.0 fHdeine StemWidth 0.1 fHiene ctemHeight 15 ‘tiene EyeWilh 03 ‘tiene EyeHeight 0.2 dene Novecth 02 ‘Heinle NoveHeight 0.2 fHicine NTeethPerRow T fHdefne Too Width 0.089833 ‘Hieine TootHeight 0.15, ‘These values are the ones used to produce the pumpkin shown in the diegrem, and you should be able to figure out what each constant means by looking at the picture. Your program must be written so thet changing any of these constants changes the picture in the appropriate way. For exemple, if you change NTeetiPerRow to 4, the new diagram should have only four teeth in each rov, but the mouth should sill be centered horizontally. The two eyes end the mouth of the pumpkin face should be drawn halfway from the center to the edge of the circle in the appropriate direction, so thet changing HeadRadue also changes the positions at which these features are drawn The center of the circle representing the pumpkin should appear at the center of the screen. If you wented a house to go elong with the Helloween pumpkin you designed in exercise 7, you might went to draw a diagram of the House of Usher, which Edgar Allen Poe describes as follows: I locked upon the scene before me...upon the bleak wells—upon the vacant eye- like window s...with an utter desperation of soul. Fran Poe's description, you might image a house thet looks something like this: ‘White @ program thet draws the house illustrated in the diagram, using the following constents to specify the various dimensions ‘dene HouseWth 15 ‘dente HouseHeight 20 tiene HouseArch 1.0, fHdeine Twoer Wid 0.4 ‘dente TowerHeight 23 Heinle TowerArch 08 Hine Doce 0.3 tiene Dooreight 5 tHdene Doorrch 0.25 fHicfine WindonLevel 1.4 fHicine Window Size 03 ‘The constants whose names end in Arch specify the height of the trimgular portion on top of the rectangular base, the windows are assumed to be square and therefare have only the single dimension Window Sisze 9. Write « program thet draws the following stylized picture of the Lincoln Memorial in ‘Weshington, D.C 0000000000 dq f As in exercises 7 and 8, your program should use the following constents to define the characteristics of the picture: fHiene MerorilWidth 40, tHicne Pesectaheight 03, fHiefine NumberOfCohenne 12 fHieine Colunniidth 0.14 ‘deine ColurnHeight 1.0 ‘icine Column GrcleRadue 0.05, fHiefne LowerRoo Height 03 fHécne UpperRoof ith 3.5 ‘Hdefne UpperRootHeight 03 fHiene Statue Eid 0.1 fHieine Statue Heght 0.2 ‘Note that NumberOfCohmns is one of the constants thet define the picture. In designing your progam, you should be swe thet it is possible to change the value of NumberOfColumns and still have the columns come out equally spaced across the width of the memorial. 10. White a function DrewShadedBox thet draws @ box whose interior is shaded by closely spaced diegonal lines throughout the entire figure. The function should take a fifth pecameter (after the four used in DenBo)) that specifies the distance between each of the sheding line, measured along the edges of the box rather then diegonelly,. The shading separation peremeter should be en integer measwredin peints, « ust of measure fevored bby printers and typesetters thet is equal to 1/72 of eninch For exemple, the function call DOrwShoeBox (10,10, 20,015, 5), should produce the following output 11. Use the DrwShadedSox Function from exercise 10 es past of a mein program to draw checkerboard, for which the edge length of each square is 0.25 inches and the sanding separation for the dask squares is 3 points. The program should remit in the following figure:

You might also like