C++ line() - Draw a Line on the Screen

- July 12, 2018
line function cpp


In C++, the line() function is used to draw a line between two given points on the screen. This function is located in "graphics.h" header file.

Syntax of line() Function

The general syntax of this function looks like:
line (x1, y1, x2, y2);

Where:
x1 & y1 represent the x & y co-ordinates of first point.
x2 & y2 represent the x & y co-ordinates of second point.


All the above mentioned parameters may be variables or values of "int" data type.

How to Use line() Function?

To draw a line between left upper corner and right bottom corner of the screen for VGA monitor, the statement will be as follows:

line (0, 0, 639, 479);

OR
line (639, 479, 0, 0);

In the above statements, point (0, 0) represents the upper left corner of the screen and point (639, 479) represents the bottom right corner of the screen.

In the same way, to draw a line between bottom left corner & upper right corner of the VGA screen, the statement will be as follows:

line (0, 639, 479, 0);
OR
line (639, 0, 0, 479);

In the above statement, point (0, 479) represents the bottom left corner of the screen and point (638, 0) represents the upper right corner of the screen.

Example of line() Function

The following C++ program draws lines starting from left upper corner to right upper corner. Where the center point is (320, 240).

#include<iostream>
#include<canio>
#include<graphics>
using namespace std;
  main()
   {
      int d, m, r, co, x1;
      driver = DETECT;
      initgraph (&d, &m, " ");
      cleardevice();
      for (co = 1, x1 = 1; x1<= 640; co++, x1+= 5)
      {
         setcolor (co);
         line(320, 240, x1, 0);
         if (co >= 15) co = 1;
      }
  getch();
  closegraph();
}

Leave your reply.
EmoticonEmoticon