Home » C Program to Draw a Polygon Shape

C Program to Draw a Polygon Shape

The C programming language graphics support allows creating polygon shapes with N points. Each of these N points must be a pair of coordinates. In this article, you will write a program to draw a polygon shape in C language.

Problem Definition

We wish to create a polygon shape with 4 points. Each of the points will be represented using a pair (x, y) where x is x-coordinate and y is y-coordinate in the x-axis and y-axis respectively.

The program must go through the following steps to create a polygon:

  1. Declare all variables including graphics variables and polygon array.
  2. Initialize all variables.
  3. Initialize the graph while the path is set to the graphics driver.
  4. Assign values to polygon array in pairs.
  5. Use drawpoly( ) function to draw the polygon shape.
  6. Close the graph.

Program Code – Polygon using drawpoly( )

/* C Program to draw a Polygon in C language */

#include <graphics.h>
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

int main()
{
/* Declaring a variable */

int gdriver, gmode;

/* Polygon array to define points on the polygon shape */

int poly[10];

/* Initialize the variables */

gdriver = DETECT;

/* Initialize the graph and set path to BGI files */

initgraph(&gdriver, &gmode, "D:\\TURBOC3\\BGI");

/* Polygon Points in Pairs */


poly[0] = 20; /* 1st vertex */
poly[1] = 100;

poly[2] = 120;
poly[3] = 140; /* 2nd vertex */

poly[4] = 240;
poly[5] = 260; /* 3rd vertex */

poly[6] = 120;
poly[7] = 320; /* 4th vertex */

poly[8] = poly[0];
poly[9] = poly[1]; /* The polygon does not
close automatically, so we close it */

/* Draw the Polygon */

drawpoly(5, poly);

getch();

/* Close the graph */

closegraph();
return 0;

}

Output

Output - drawpoly() function
Output – Using drawpoly() function
(adsbygoogle = window.adsbygoogle || []).push({}); </script

Please support us by disabling your adblocker or whitelist this site from your adblocker. Thanks!

turn of adblocker imag

(adsbygoogle = window.adsbygoogle || []).push({});