MidPoint Line Drawing Algorithm in C and C++
Here, you will know about Midpoint Line Algorithm and get the program code of Midpoint Line Drawing Algorithm in C and C++ using computer graphics.
Line Drawing Algorithm in Computer Graphics
There are three algorithms available to draw line in computer graphics.
1. DDA(Digital Differential Analyzer) Line Drawing Algorithm
2. Bresenham Line Drawing Algorithm
3. Mid Point Line Drawing Algorithm
Here, you will learn Mid Point Line Drawing Algorithm
What is MidPoint Line Drawing Algorithm
Midpoint line drawing algorithm is used to draw a line between two points in computer graphics. It works by calculating the distance from the start and end points and then determining the midpoint.
Midpoint algorithm iteratively draws a line between the start or end point, where the midpoint lies. This continues until the start and end points are connected.
Program for MidPoint Line Drawing Algorithm in C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | //Program for Midpoint Line Drawing Algorithm in C #include<stdio.h> #include<conio.h> #include<graphics.h> void midPoint(int X1, int Y1, int X2, int Y2) { int dx = X2 - X1; int dy = Y2 - Y1; if(dy<=dx){ int d = dy - (dx/2); int x = X1, y = Y1; printf("%d%dn", x, y); while (x < X2) { x++; if (d < 0) d = d + dy; else { d += (dy - dx); y++; } printf("%d%dn", x, y); } } else if(dx<dy) { int d = dx - (dy/2); int x = X1, y = Y1; printf("%d%dn", x, y); while (y < Y2) { y++; if (d < 0) d = d + dx; else { d += (dx - dy); x++; } printf("%d%dn", x, y); putpixel(x,y,15); } } }int main() { int gd = DETECT, gm; initgraph(&gd, &gm, "c:\turboc3\bgi"); int X1 = 100, Y1 = 100, X2 = 110, Y2 = 112; printf("nnnMidpoint Line Drawing Algorithmn"); midPoint(X1, Y1, X2, Y2); getch(); return 0; } |
Program for MidPoint Line Drawing Algorithm in C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | //Program for Midpoint Line Drawing Algorithm in C++ #include<iostream.h> #include<conio.h> #include<graphics.h> void midPoint(int X1, int Y1, int X2, int Y2) { int dx = X2 - X1; int dy = Y2 - Y1; if(dy<=dx){ int d = dy - (dx/2); int x = X1, y = Y1; cout << x << "," << y << "n"; while (x < X2) { x++; if (d < 0) d = d + dy; else { d += (dy - dx); y++; } cout << x << "," << y << "n"; } } else if(dx<dy) { int d = dx - (dy/2); int x = X1, y = Y1; cout << x << "," << y << "n"; while (y < Y2) { y++; if (d < 0) d = d + dx; else { d += (dx - dy); x++; } cout << x << "," << y << "n"; putpixel(x,y,15); } } }int main() { int gd = DETECT, gm; initgraph(&gd, &gm, "c:\turboc3\bgi"); cout<<"nnnMidpoint Line Drawing Algorithmn"; int X1 = 100, Y1 = 100, X2 = 110, Y2 = 112; midPoint(X1, Y1, X2, Y2); getch(); return 0; } |
Output: