The Liang-Barsky algorithm uses the parametric equation of a line and inequalities describing the range of the clipping box to determine the intersections between the line and the clipping box. With these intersections it knows which portion of the line should be drawn. This algorithm is significantly more efficient than Cohen-Sutherland.

Liang and Barsky have created an algorithm that uses floating-point arithmetic but finds the appropriate end points with at most four computations. This algorithm uses the parametric equations for a line and solves four inequalities to find the range of the parameter for which the line is in the viewport.

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

struct point
{
	float x;
	float y;
};

struct box
{
	int xx, yx, yn, xn;
};


void clipline(box b,point p1, point p2)
{
	float p[4],q[4],r[4];
	point p3;
	int dx=p2.x-p1.x;
	int dy=p2.y-p1.y;
	p[0]=-dx;
	p[1]=dx;
	p[2]=-dy;
	p[3]=dy;
	q[0]=p1.x-b.xn;
	q[1]=b.xx-p1.x;
	q[2]=p1.y-b.yn;
	q[3]=b.yx-p1.y;
	float big=0;
	float small=1;
	for (int i=0;i<4;i++)
		if (p[i]==0 &&q[i]<0)
			return;
	for (i=0;i<4;i++)
	{
		r[i]=q[i]/p[i];
		if (p[i]<0)
		{
			if (r[i]>small)
				return;
			if (r[i]>big&&r[i]>0&&r[i]<1)
				big=r[i];
		}
		else
		{
			if (r[i]<big)
            	return;
			if (r[i]<small&&r[i]>0&&r[i]<1)
				small=r[i];
		}
	}
	p3.x=p1.x+small*dx;
	p3.y=p1.y+small*dy;
	p2.x=p1.x+big*dx;
	p2.y=p1.y+big*dy;
	line(p3.x+getmaxx()/2,getmaxy()/2-p3.y,p2.x+getmaxx()/2,getmaxy()/2-p2.y);
}

void main()
{
	point p1,p2;
	box b;
	int gdriver = DETECT, gmode = VGAHI;
	initgraph(&gdriver, &gmode, "");
	int x1,y1,x2,y2,xx,xn,yx,yn;
	b.xx=getmaxx()/4;
	b.xn=-getmaxx()/4;
	b.yn=-getmaxy()/4;
	b.yx=getmaxy()/4;
	rectangle (getmaxx()/2+b.xn,getmaxy()/2-b.yn,b.xx+getmaxx()/2,getmaxy()/2-b.yx);
	cout<<"Enter the line's co-ordinates ";
	cin>>p2.x>>p2.y>>p1.x>>p1.y;
	clipline(b,p1,p2);
	getch();
}