Program to draw line using Bresenham’s algorithm

  Program to Simulate BRESENHAM’S ALGORITHM FOR LINE DRAWING.

AIM:

To write a program in C to draw a line using Bresenham’s algorithm.

ALGORITHM:

1. Start the program.

2. Initialize the variables.

3. Call the initgraph() function.

4. Input the two line end-points and store the left end-point in (x0, y0).

5. Plot the point (x0, y0).

6. Calculate the constants Δx, Δy, 2Δy, and (2Δy - 2Δx) and get the first value for the decision parameter as:

7. At each xk along the line, starting at k = 0, perform the following test. If pk < 0, the next point to plot is (xk+1, yk) and

8. Otherwise, the next point to plot is (xk+1, yk+1) and Repeat step 4 (Δx – 1) times.

xypΔ−Δ=20yppkkΔ+=+21xyppkkΔ−Δ+=+221

9. Stop the graphics driver.

10. Stop the program.

Program: 

/*-----------------------------------------------------------------------------------------   Program in C to draw a line using Bresenham’s algorithm -----------------------------------------------------------------------------------------*/ # include <stdio.h> # include <conio.h> # include <graphics.h> void main( ) { int x,y,x1,y1,x2,y2,p,dx,dy; int gdriver=DETECT,gmode; initgraph(&gdriver,&gmode,"C:\\tc\\BGI:"); printf("\nEnter the x-coordinate of the first point ::"); scanf("%d",&x1); printf("\nEnter the y-coordinate of the first point ::"); scanf("%d",&y1); printf("\nEnter the x-coordinate of the second point ::"); scanf("%d",&x2); printf("\nEnter the y-coordinate of the second point ::"); scanf("%d",&y2); x=x1; y=y1; dx=x2-x1; dy=y2-y1; putpixel(x,y,2); p=(2dy-dx); while(x<=x2) { if(p<0) { x=x+1; p=2*x-dx; } else { x=x+1; y=y+1; p=p+2*dy; } putpixel(x,y,7); } getch(); closegraph(); }

Output

Enter the x-coordinate of the first point ::40

Enter the y-coordinate of the first point ::50

Enter the x-coordinate of the second point ::60

Enter the y-coordinate of the second point ::80

RESULT:

Thus the program in C to draw the line by using Bresenham’s algorithm was done successfully.

Disqus Comments

Download YouTube videos in Python

     We can use the package Pytube to download YouTube videos in a Python script. It’s a free tool you can install from the PyPI repository....