Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Using the graphics library from Chapter 7 (from \"The Art and Science of C Progr

ID: 662882 • Letter: U

Question

Using the graphics library from Chapter 7 (from "The Art and Science of C Programming"), write a program that displays polygons on the screen. The coordinates for the vertices of a polygon are stored in a data file, one coordinate per line. Each coordinate consists of two floating point numbers enclosed in parenthesis and separated by a comma. The input file may contain vertex coordinates for several different polygons; each polygon is separated from the preceding one by a blank line in the file. For example, the file polygon.dat contains the coordinates for a square and a triangle, as follows:

polygon.dat

(0.5, 0.5)

(1.0, 0.5)

(1.0, 1.0)

(0.5, 1.0)

(2.0, 0.5)

(3.0, 0.5)

(2.0, 1.0)

Your program should read the input file and draw the polygons on the screen. Given the input file polygon.dat, the display should look like this:

Explanation / Answer

//program for reading data file and drawpolygon

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

int main()
{
   int i=0;
   int gd=DETECT,gm; //graphics mode and graphics driver
   float *points; //dynamic float array for polygon points
   FILE *fp; //file pointer
   fp=fopen("polygon.dat","r"); //opened file for reading
   //reading from file
   while(!feof(fp)) //read until end of file
   {
       fscanf(fp,"%f",points+i); //reading each point from file
       i++; //increase points count
   }
   fclose(fp); //after reading file close file
   //drawing polygons  
   initgraph(&gd,&gm,"\tc\bgi"); //initiate graphics screen
   drawpoly(i,points); //drawing polygon
   getch(); //input key stroke
   closegraph(); //close the graph
   return 0;
}

//Here I am not putting output, because this code works on windows based Turbo C