# Cohen Sutherland Line Clipping Algorithm in C and C++

Here you will learn about cohen sutherland line clipping algorithm in C and C++.

This is one of the oldest and most popular line clipping algorithm. To speed up the process this algorithm performs initial tests that reduce number of intersections that must be calculated. It does so by using a 4 bit code called as region code or outcodes. These codes identify location of the end point of line.

Each bit position indicates a direction, starting from the rightmost position of each bit indicates left, right, bottom, top respectively.

Once we establish region codes for both the endpoints of a line we determine whether the endpoint is visible, partially visible or invisible with the help of ANDing of the region codes.

There arises 3 cases which are explained in the algorithm below in step 4.

Also Read: Liang Barsky Line Clipping Algorithm in C and C++

### Algorithm

1. Read 2 end points of line as p1(x1,y1) and p2(x2,y2)

2. Read 2 corner points of the clipping window (left-top and right-bottom) as (wx1,wy1) and (wx2,wy2)

3. Assign the region codes for 2 endpoints p1 and p2 using following steps:-

initialize code with 0000

Set bit 1 if x<wx1

Set bit 2 if x>wx2

Set bit 3 if y<wy2

Set bit 4 if y>wy1

4. Check for visibility of line

1. If region codes for both endpoints are zero then line is completely visible. Draw the line go to step 9.
2. If region codes for endpoints are not zero and logical ANDing of them is also nonzero then line is invisible. Discard the line and move to step 9.
3. If it does not satisfy 4.a and 4.b then line is partially visible.

5. Determine the intersecting edge of clipping window as follows:-

1. If region codes for both endpoints are nonzero find intersection points p1’ and p2’ with boundary edges.
2. If region codes for any one end point is non zero then find intersection point p1’ or p2’.

6. Divide the line segments considering intersection points.

7. Reject line segment if any end point of line appears outside of any boundary.

8. Draw the clipped line segment.

9. Stop.

## Program for Cohen Sutherland Line Clipping Algorithm in C and C++

### C++ Program

Output

Before Clipping

After Clipping

Comment below if you have doubts or found any information incorrect in above cohen sutherland line clipping algorithm in C and C++.

### 13 thoughts on “Cohen Sutherland Line Clipping Algorithm in C and C++”

1. Abhishek Kumar Singh

Yes, if the line doesn’t lie in the visibility region. here we obtain v=2 for line being partially inside the visibility region. Hence line clipping is done.

1. Abhishek Kumar Singh

May be the path you set in initgraph is not correct.
Simply put this line
initgraph(&gdrive,&gmode,”C:\tc\bgi”. check if your path has TC or turboC3 or anything else.