Wednesday, September 11, 2013

Tagged Under: ,

Program to draw Polygon in C

Share

Program to draw polygon in C

As a polygon can have any no. of distinct co-ordinates (min 3). Hence, we use 2 array to store X and Y coordinates. To draw line between the user provided points we can either use any line drawing algorithm like ( DDA Line drawing algorithm or Bresenham's line drawing algorithm ) or simple function LINE( ) included in <graphics.h>

Draw polygon in C

#include<stdio.h>
#include<conio.h>
#include<graphics.h>
void main()
{ int gd=DETECT,gm;
 int num,i,x[10],y[10];
 clrscr();
  printf("Enter No of Co-ordinates :"); // Min 3 Co-ordinates
  scanf("%d",&num);
  
  for(i=0;i<num;i++)
  { 
   printf(" Enter Co-ordinates for %d (X,Y)",i);
   scanf("%d %d",&x[i],&y[i]);
  }
  
  initgraph(&gd,&gm,"");
  cleardevice();
  for(i=0;i<num;i++)
  {
   line(x[i],y[i],x[((i+1)%num)],y[((i+1)%num)]); //Line function from graphics.h
  }
  getch();
}
In Case of having any problem , Please leave a comment ! :)