In: Computer Science
Programs 1 and 2 (Line Scan Conversion)
1.Write a function to draw a line using the Basic line drawing algorithm.
The following is a function header example:
Basic-alg( int x0, int y0, int x1, int y1 )
Use this function to draw N lines (N is provided by the user) at positions (i.e., end coordinates) determined by a random number generator.
2.Write a function to draw a line using the "Bresenham" algorithm.
The following is a header example:brz ( int x0, int y0, int x1, int y1 )Use this function to draw N lines(N is provided by the user) at positions(i.e., end coordinates)determined by a random number generator.
NOTES:
Each of the line functions must handle all types of lines (horizontal, vertical,and all other line orientations)
1. CODE:
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
#include<graphics.h>
//Function for finding absolute value
int abs (int n)
{
return ( (n>0) ? n : ( n * (-1)));
}
//basic Function for line generation
void Basic_alg(int X0, int Y0, int X1, int Y1)
{
// calculate dx & dy
int dx = X1 - X0;
int dy = Y1 - Y0;
// calculate steps required for generating
pixels
int steps = abs(dx) > abs(dy) ? abs(dx) :
abs(dy);
// calculate increment in x & y for each
steps
float Xinc = dx / (float) steps;
float Yinc = dy / (float) steps;
// Put pixel for each step
float X = X0;
float Y = Y0;
for (int i = 0; i <= steps; i++)
{
putpixel (X,Y,RED); // put pixel at
(X,Y)
X += Xinc;
// increment in x at each step
Y += Yinc;
// increment in y at each step
delay(10);
// for visualization of line-
// generation step by step
}
}
// Driver program
int main()
{
int gd = DETECT, gm;
int n, i, x0, y0, x1, y1;
printf("Enter the number of lines: ");
scanf("%d", &n);
// Initialize graphics function
initgraph (&gd, &gm, "");
for(i=0;i<n;i++){
srand(time(NULL));
x0 = rand()%400;
y0 = rand()%400;
x1 = rand()%400;
y1 = rand()%400;
Basic_alg(x0, y0, x1, y1);
}
getch();
return 0;
}
2. CODE
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
#include<graphics.h>
void brz(int x0, int y0, int x1, int y1)
{
int dx, dy, p, x, y;
dx=x1-x0;
dy=y1-y0;
x=x0;
y=y0;
p=2*dy-dx;
while(x<x1)
{
if(p>=0)
{
putpixel(x,y,7);
y=y+1;
p=p+2*dy-2*dx;
}
else
{
putpixel(x,y,7);
p=p+2*dy;
}
x=x+1;
}
}
// Driver program
int main()
{
int gd = DETECT, gm;
int n, i, x0, y0, x1, y1;
printf("Enter the number of lines: ");
scanf("%d", &n);
// Initialize graphics function
initgraph (&gd, &gm, "");
for(i=0;i<n;i++){
srand(time(NULL));
x0 = rand()%400;
y0 = rand()%400;
x1 = rand()%400;
y1 = rand()%400;
brz(x0, y0, x1, y1);
}
getch();
return 0;
}