CSC115 C Programming

C ProgrammingTU Board 2078Unit 11

Write a program to draw a line using graphics function.

5

Answer

C graphics programs use the functions in <graphics.h> (Turbo C / WinBGIm). The graphics system must first be switched on with initgraph(), and closed with closegraph() at the end.

The line(x1, y1, x2, y2) function draws a straight line from point (x1, y1) to point (x2, y2). The origin (0, 0) is the top-left corner of the screen, and y grows downwards.

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

int main(void) {
    int gd = DETECT, gm;          /* detect the graphics driver automatically */

    initgraph(&gd, &gm, "");      /* path to BGI files, "" if they are in the current folder */

    setcolor(WHITE);
    line(100, 100, 400, 250);     /* line from (100,100) to (400,250) */
    outtextxy(100, 80, "Line from (100,100) to (400,250)");

    getch();                      /* wait for a key before closing */
    closegraph();
    return 0;
}

Explanation

  • gd = DETECT asks the system to pick the best graphics driver, and gm receives the graphics mode.
  • initgraph() loads the driver and switches the screen to graphics mode.
  • setcolor() sets the drawing colour, and line() draws the line.
  • closegraph() releases the graphics system and returns to text mode.

Discussion

Loading…

All C Programming old questions