CSC115 ยท 2081 ยท 5 marks
Write a program to draw two shapes of your choice using graphics function.
Write a program to draw two shapes of your choice using graphics function. [5]
C ProgrammingChapter 11: Introduction to GraphicsGraphics Function
Quick answer
The two shapes chosen are a Circle and a Rectangle, both drawn using standard graphics functions from graphics.h.
Program to Draw Two Shapes Using Graphics Functions
Answer
Program
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
void main()
{
int gd = DETECT, gm;
/* Initialize the graphics mode */
initgraph(&gd, &gm, "c:\\tc\\bgi");
/* Shape 1: Draw a Circle
center at (200, 150) with radius 80 */
setcolor(WHITE);
circle(200, 150, 80);
/* Shape 2: Draw a Rectangle
top-left corner at (350, 100)
bottom-right corner at (550, 250) */
setcolor(WHITE);
rectangle(350, 100, 550, 250);
getch();
/* Close the graphics mode */
closegraph();
}
Explanation of Each Step
| Step | Description |
|---|---|
int gd = DETECT, gm; | Declares graphics driver and mode variables. DETECT auto-detects the driver. |
initgraph(&gd, &gm, "c:\\tc\\bgi") | Initializes the graphics system and opens a graphics window. The path points to the BGI driver files. |
setcolor(WHITE) | Sets the current drawing color to white. |
circle(200, 150, 80) | Draws a circle with center at pixel (200, 150) and radius 80 pixels. |
rectangle(350, 100, 550, 250) | Draws a rectangle with top-left corner at (350, 100) and bottom-right corner at (550, 250). |
getch() | Waits for a key press so the output window stays visible. |
closegraph() | Closes the graphics mode and returns to text mode. |
Output
+------------------------------------------+
| |
| ( Circle ) [ Rectangle ] |
| drawn at drawn at |
| (200,150) (350,100) to |
| r = 80 (550,250) |
| |
+------------------------------------------+
Note: The pixel origin (0, 0) is at the top-left corner of the screen. All coordinates are measured in pixels from this origin.
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.