computer graphics and algorithms lab manual

95
Ex.No:1 IMPLEMENTATION OF BRESENHAM’S ALGORITHM DATE: LINE, CIRCLE, ELLIPSE. LINE: AIM: To study and Implement Bresenham's Line Drawing Algorithm ALGORITHM: STEP 1: Input the two line endpoints and store the left end point in (x 0 ,y 0 ). STEP 2: Load (x 0 ,y 0 ) into the frame buffer,that is,plot the first point. STEP 3: Calculate constants Δx,Δy,2Δy,and 2Δy-2Δx,and obtain the starting value for the decision parameter as p 0 =2Δy-Δx STEP 4: At each x,along the line,starting at k=0,perform the following test. if p k < 0,the next point to plot is (x k +1,y k )and p k+1 =p k +2Δy otherwise,the next point to plot is (x k +1,y k +1)and p k+1 =p k +2Δy-2Δx STEP 5: Repeat step 4Δx times. SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024 www.jntuworld.com www.jntuworld.com www.jwjobs.net

Upload: alex-solomon-a

Post on 27-Dec-2015

68 views

Category:

Documents


7 download

DESCRIPTION

lab manual

TRANSCRIPT

Page 1: Computer Graphics and Algorithms Lab Manual

Ex.No:1 IMPLEMENTATION OF BRESENHAM’S ALGORITHM

DATE: LINE, CIRCLE, ELLIPSE.

LINE:

AIM:To study and Implement Bresenham's Line Drawing Algorithm

ALGORITHM:

STEP 1: Input the two line endpoints and store the left end point in (x0,y0).

STEP 2: Load (x0,y0) into the frame buffer,that is,plot the first point.

STEP 3: Calculate constants Δx,Δy,2Δy,and 2Δy-2Δx,and obtain the starting value for the

decision parameter as p0=2Δy-Δx

STEP 4: At each x,along the line,starting at k=0,perform the following test. if pk< 0,the next

point to plot is (xk+1,yk)and pk+1=pk+2Δy otherwise,the next point to plot is

(xk+1,yk+1)and pk+1=pk+2Δy-2Δx

STEP 5: Repeat step 4Δx times.

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 2: Computer Graphics and Algorithms Lab Manual

Program:

LINE

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

#include<graphics.h>

#define MINX 0

#define MINY 0

void begin();

int scale_x,scale_y,x_factory_factor;

void main()

int x,y,x0,y0,xn,yn,dx,dy,p,twody,twodydx,xend;

char te[20];

int d=DETECT,b;

int CENTREX,CENTREY,MAXX,MAXY;

printf(" \n enter the starting points:");

scanf(" %d %d",&x0,&y0);

printf("\n enter the end points:");

scanf(" %d%d",&xn,&yn);

printf("\n");

clrscr();

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 3: Computer Graphics and Algorithms Lab Manual

initgraph(&d,&b,"");

cleardevice();

setgraphmode(getgraphmode());

CENTREX=getmaxx()/2;

CENTREY=getmaxy()/2;

begin();

dx=abs(x0-xn);

dy=abs(y0-yn);

p=2*dy-dx;

twody=2*dy;

twodydx=2*(dy-dx);

if(x0>xn)

x=xn;

y=yn;

xend=x0;

else

x=x0;

y=yn;

xend=xn;

putpixel(CENTREX+x,CENTREY+y,3);

while(x<xend)

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 4: Computer Graphics and Algorithms Lab Manual

x++;

if(p<0)

p=p+twody;

else

y++;

p=p+twodydx;

putpixel(CENTREX+x,CENTREY+y,3);

getch();

closegraph();

void begin()

int CENTREX=getmaxx()/2;

int CENTREY=getmaxy()/2;

int MAXX=getmaxx();

//int MAXY=getmaxx();

line(0,getmaxy()/2,getmaxx(),getmaxy()/2);

line(getmaxx()/2,0,getmaxx()/2,getmaxx());

setcolor(50);

settextstyle(0,0,0);

outtextxy(CENTREX+2,CENTREY+5,"ORIGIN");

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 5: Computer Graphics and Algorithms Lab Manual

outtextxy(MAXX-40,CENTREY+4,"FIRST");

outtextxy(CENTREX+5,5,"SECOND");

OUTPUT:

Enter the starting points:0 0

Enter the end points:100 100

SECOND

ORIGIN

FIRST

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 6: Computer Graphics and Algorithms Lab Manual

RESULT:Thus the program for implementation of Bresenham’s line drawing Algorithm is successfully compiled and executed.

CIRCLE:

AIM:To study and Implement Bresenham's Circle Drawing Algorithm

ALGORITHM:

STEP 1: Input radius r and circle center(xc,yc) and obtain the first point on the circumference of the circle centered on the origin as (x0,y0)=(0,r)

STEP 2: Calculate the initial value of the decision parameter as p0=5/4-r

STEP 3: At each xk position,starting at k=0,perform the following test:

If pk<0 ,the next point along the circle centered on(0,0) is(xk+1,yk) and

Pk+1=pk+2xk+1 + 1

Otherwise the next point along the circle is(xk+1,yk-1) and pk+1=pk+2xk+1 +1 +2yk+1 where 2xk+1=2xk+2 and 2yk+1=2yk-2

STEP 4: Determine the symmetry points in the other seven octants

STEP 5:Move each calculated pixel position (x,y) on to the circular path centered on (xc,yc) and plot the coordinate values:

x=x+x0, y=y+yc

STEP 6: Repeat steps 3 through 5 until x>=y

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 7: Computer Graphics and Algorithms Lab Manual

CIRCLE:

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

#include<dos.h>

#include<graphics.h>

#define cenx 320

#define ceny 240

#define MAXX 639

#define MAXY 479

#define MINX 0

#define MINY 0

void main()

void cir(int a,int b,int c);

int gd=DETECT,gm;

int xcent,ycent,radi;

printf("\n center coordinates");

scanf("%d%d",&xcent,&ycent);

printf("\n Enter the radius");

scanf("%d",&radi);

clrscr();

initgraph(&gd,&gm,"");

cleardevice();

setbkcolor(BLUE);

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 8: Computer Graphics and Algorithms Lab Manual

cir(xcent,ycent,radi);

getch();

closegraph();

void cir(int xc,int yc,int radius)

void plotpoints(int a,int b,int c,int d);

int p,x,y;

line(getmaxx()/2,0,getmaxx()/2,getmaxx());

line(0,getmaxy()/2,getmaxx(),getmaxy()/2);

setbkcolor(111);

x=0;

y=radius;

plotpoints(xc,yc,x,y);

p=1-radius;

while(x<y)

if(p<0)

x++;

else

x++;

y--;

if(p<0)

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 9: Computer Graphics and Algorithms Lab Manual

p=p+(2*x)+1;

else

p=p+(2*(x-y))+1;

plotpoints(xc,yc,x,y);

void plotpoints(int xc,int yc,int x,int y)

putpixel(cenx+xc+x,ceny-yc+y,4);

putpixel(cenx+xc-x,ceny-yc+y,4);

putpixel(cenx+xc+x,ceny-yc-y,4);

putpixel(cenx+xc-x,ceny-yc-y,4);

putpixel(cenx+xc+y,ceny-yc+x,4);

putpixel(cenx+xc-y,ceny-yc+x,4);

putpixel(cenx+xc+y,ceny-yc-x,4);

putpixel(cenx+xc-y,ceny-yc-x,4);

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 10: Computer Graphics and Algorithms Lab Manual

OUTPUT:

Enter co-ordintaes :0 0

Enter the radius:100

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 11: Computer Graphics and Algorithms Lab Manual

RESULT:

Thus the program for implementation of Bresenham’s circle drawing Algorithm is successfully compiled and executed.

ELLIPSE:

AIM:To study and Implement Bresenham's Ellipse Drawing Algorithm

ALGORITHM:

STEP 1:Input rx,ry and ellipse center (xc,yc) and obtain the first point on an ellipse centered on the origin as (x0,y0)=(0,r)

STEP 2: Calculate the initial value of the decision parameter in region 1 as

P10=r2y-r2xry+1/4r2x

STEP 3: At each xk position in region 1,starting at k=0,perform the following test:

If p1k<0,the next point along the ellipse centered on (0,0) is (xk+1,yk) and

P1k+1=p1k+2r2yxk+1+r2y

Otherwise the next point along the circle is (xk+1,yk-1) and

P1k+1=p1k+2r2yxk+1-2r2xyk+1+r2y

STEP 4:Calculate the initial value of the decision parameter in region 2 using the last point (x0,y0) calculated in region 1 as

STEP 5:At each position in region 2,starting at k=0,perform the following test:

If p2k>0,the next point along the ellipse centered on(0,0) is (xk,yk-1) and

STEP 6:Determine the symmetry points in the other three quadrants

STEP 7:Move each calculated pixel position(x,y) onto the elliptical path centered on(xc,yc) and plot the coordinate values: x=x+x0 y=y+y0

STEP 8:Repeat the steps for region1 until 2r2yx>=2r2xy

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 12: Computer Graphics and Algorithms Lab Manual

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 13: Computer Graphics and Algorithms Lab Manual

ELLIPSE:

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

#include<graphics.h>

#include<math.h>

float p,rx2,ry2,xc,yc,x,y,ry,rx,try2,trx2,px,py;

float na;

int r;

int errorcode;

void plot()

int k;

putpixel(xc+x,yc+y,BLUE);

putpixel(xc-x,yc+y,BLUE);

for(k=xc-x;k<=xc+x;k++)

putpixel(xc+x,yc-y,BLUE);

putpixel(xc-x,yc-y,BLUE);

void brell()

plot();

ry2=ry*ry;

rx2=rx*rx;

try2=2*ry2;

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 14: Computer Graphics and Algorithms Lab Manual

trx2=2*rx2;

x=0;

y=ry;

plot();

na=(float)(r*(2/4));

if((na)+0.5<na)

na=ceil(na);

else

p=ry2-rx2*ry+na;

px=0;

py=trx2*y;

while(px<py)

x++;

px+=try2;

if(p>=0)

y--;

py=py-trx2;

if(p<0)

p+=ry2+px;

else

p=p+ry2+px-py;

plot();

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 15: Computer Graphics and Algorithms Lab Manual

na=ceil((float)(x+0.5));

p=ry2*(na)*(na)+rx2*(y-1)*(y-1)-rx2*ry2;

while(y>0)

y--;

py-=trx2;

if(p<0)

x++;

px+=try2;

if(p>0)

p+=rx2-py;

else

p+=rx2-py+px;

plot(1);

getch();

closegraph();

void main()

int gd=DETECT,gm,errorcode;

clrscr();

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 16: Computer Graphics and Algorithms Lab Manual

printf("\n enter the xradius");

scanf("%f",&rx);

printf("\n enter the yradius");

scanf("%f",&ry);

clrscr();

initgraph(&gd,&gm,"");

setbkcolor(7);

line(getmaxx()/2,0,getmaxx()/2,getmaxx());

line(0,getmaxy()/2,getmaxx(),getmaxy()/2);

xc=getmaxx()/2;

yc=getmaxy()/2;

brell();

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 17: Computer Graphics and Algorithms Lab Manual

OUTPUT:

Enter the X radius: 100

Enter the Y radius: 150

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 18: Computer Graphics and Algorithms Lab Manual

RESULT:

Thus the program for implementation of Bresenham’s ellipse drawing Algorithm is successfully compiled and executed.

Ex.No: 2 LIINE, CIRCLE AND ELLIPSE ATTRIBUTES

DATE:

AIM: To study and Implement of Line attributes by using opengl.

ALGORITHM:

STEP 1:This program demonstrates geometric primitives and their attributes.Using OpenGL Graphics Library to perform properties of output primitives.Include all header file such as glut.h,stdlib.h etc.,

STEP 2:Using glvertex2f to specify point ,line and polygon vertices within glbegin and glendInitialize the properties of line (color and shade)

STEP 3:Glshademodel specifies a symbolic value representing a shading technique. Accepted values are GL_FLAT and GL_SMOOTH.

STEP 4:Glclear(GL_COLOR-BUFFER-BIT) clear buffer to preset values and indicating the buffer currently enabled for color writing.

STEP 5:Glenable() to specify the enable or disable GL capability.Glinestipple(Glint factor,Pattern) to specify thr line stipple pattern.

STEP 6:Set the viewport glviewport(x,y,w,h)Glmatrixmode(GL_projection) specifying which matrix stack is the target for subsequent matrix operation.

STEP 7:Glloadidentity function replaces the current matrix with the identify matrix.Glortho2d to specify the 2d orthographic viewing region

STEP 8:Initialize the glut libraryInitialize the display mode GLUT_SINGLE(bit mask to select single buffered windows) and GLUT_RGB(bit mask to select the rgb)

STEP 9:Using Input events to perform following operationglutReshapeFunc() - what actions to be taken when the window is resized, moved or exposed.

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 19: Computer Graphics and Algorithms Lab Manual

glutKeyboardFunc() - links a key with a routine that is invoked when a key is pressed. glutSpecialFunc() - F1, F2, F3 etc.glutMouseFunc() - links a mouse button with a routine that is invoked when the mouse button is pressed/released.

STEP 10:Stop the program.

PROGRAM:

#include <glut.h>#include <stdlib.h>#define drawOneLine(x1,y1,x2,y2) glBegin(GL_LINES); glVertex2f ((x1),(y1)); glVertex2f ((x2),(y2)); glEnd();void init(void) glClearColor (0.0, 0.0, 0.0, 0.0); glShadeModel (GL_FLAT);void display(void) int i; glClear (GL_COLOR_BUFFER_BIT);

/* select white for all lines */ glColor3f (1.0, 1.0, 1.0);

/* in 1st row, 3 lines, each with a different stipple */ glEnable (GL_LINE_STIPPLE); glLineStipple (1, 0x0101); /* dotted */ drawOneLine (50.0, 125.0, 150.0, 125.0); glLineStipple (1, 0x00FF); /* dashed */ drawOneLine (150.0, 125.0, 250.0, 125.0); glLineStipple (1, 0x1C47); /* dash/dot/dash */ drawOneLine (250.0, 125.0, 350.0, 125.0);/* in 2nd row, 3 wide lines, each with different stipple */ glLineWidth (5.0); glLineStipple (1, 0x0101); /* dotted */ drawOneLine (50.0, 100.0, 150.0, 100.0); glLineStipple (1, 0x00FF); /* dashed */ drawOneLine (150.0, 100.0, 250.0, 100.0); glLineStipple (1, 0x1C47); /* dash/dot/dash */

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 20: Computer Graphics and Algorithms Lab Manual

drawOneLine (250.0, 100.0, 350.0, 100.0); glLineWidth (1.0);/* in 3rd row, 6 lines, with dash/dot/dash stipple *//* as part of a single connected line strip */ glLineStipple (1, 0x1C47); /* dash/dot/dash */ glBegin (GL_LINE_STRIP); for (i = 0; i < 7; i++) glVertex2f (50.0 + ((GLfloat) i * 50.0), 75.0); glEnd ();/* in 4th row, 6 independent lines with same stipple */ for (i = 0; i < 6; i++) drawOneLine (50.0 + ((GLfloat) i * 50.0), 50.0, 50.0 + ((GLfloat)(i+1) * 50.0), 50.0); /* in 5th row, 1 line, with dash/dot/dash stipple *//* and a stipple repeat factor of 5 */ glLineStipple (5, 0x1C47); /* dash/dot/dash */ drawOneLine (50.0, 25.0, 350.0, 25.0); glDisable (GL_LINE_STIPPLE); glFlush ();void reshape (int w, int h) glViewport (0, 0, (GLsizei) w, (GLsizei) h); glMatrixMode (GL_PROJECTION); glLoadIdentity (); gluOrtho2D (0.0, (GLdouble) w, 0.0, (GLdouble) h);void keyboard(unsigned char key, int x, int y) switch (key) case 27: exit(0); break; int main(int argc, char** argv) glutInit(&argc, argv); glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); glutInitWindowSize (400, 150); glutInitWindowPosition (100, 100); glutCreateWindow (argv[0]); init (); glutDisplayFunc(display); glutReshapeFunc(reshape); glutKeyboardFunc(keyboard); glutMainLoop();

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 21: Computer Graphics and Algorithms Lab Manual

return 0;

OUTPUT:

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 22: Computer Graphics and Algorithms Lab Manual

RESULT:

Thus the program for implementation of Line, circle and ellipse Attributes are successfully compiled and executed.

Ex No:3 (a) TWO DIMENSIONAL TRANSFORMATIONS

DATE: TRANSLATION,ROTATION,SCALING,REFLECTION,SHEAR

AIM: To study and Implement 2D Transformation

ALGORITHM:

STEP 1:Start the program

STEP 2:Include the required variables and the graphics mode specifying the path.

STEP 3:Get the vertices and get the coordinates in each case.Get the options then using the suited case to follow transformation.

STEP 4:If the option1 get the tx and ty coordinate then perform the translation operation.Point[i]=point[i]+tx and point[i+1]=point[i+1]+ty

STEP 5:Repeat the operation for all the coordinates.

STEP 6:If option2 get the sx and sy coordinates then perform the scaling operation point[i]=point[i]*sx;Point[i+1]=point[i+1]*sy;

STEP 7:Repeat the operation for all coordinates.

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 23: Computer Graphics and Algorithms Lab Manual

STEP 8:Display the output result. If the option is 3 get the rotation angle(r) then perform the rotation operation and find the r1=r1*(3.14)/(180)Point[i]=point[i]*cos(r1)-point[i+1]*sin(r1)Point[i+1]=point[i]*sin(r1)-point[i+1]*cos(r1)

STEP 9:Repeat the operation for all the coordinates

STEP 10:Display the output result

STEP 11:If the option is 4 perform the reflection operation such that Temp[i]=point[i]Point[i]=point[i+1]Point[i+1]=temp[i]Repeat the operation for all the coordinates.

STEP 12:if the option is 5 get the shearing coordinates about x axis as shx and perform the shearing operation such as point[i]=point[i]+(shx*point[i+1]);Point[i+1]=point[i+1]Repeat the steps for all coordinates

STEP 13:If option 6 exit the program

STEP 14.:Stop the program.

PROGRAM:

#include<stdio.h>

#include<conio.h>

#include<math.h>

#include<graphics.h>

void main()

int gd=DETECT,gm;

float tx,ty,sx,sy,theta;

int x[10],y[10],i,n,ch,xf,yf,xr,yr,angle;

do

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 24: Computer Graphics and Algorithms Lab Manual

clrscr();

printf("\t\t\tTransformation of an Object");

printf("\n1.Transforamtion \n2.Scaling\n3.Scalinf of an Fixed point\n4.Rotaion\n5.Rotation of an fixed point\n6.Exit");

printf("\n Enter your choice");

scanf("%d",&ch);

if(ch==6)

exit(6);

printf("\n Enter the total number of vertices");

scanf("%d",&n);

printf("Enter the co ordinates:");

for(i=1;i<=n;i++)

scanf("%d%d",&x[i],&y[i]);

initgraph(&gd,&gm,"");

for(i=1;i<n;i++)

line(x[i],y[i],x[i+1],y[i+1]);

line(x[n],y[n],x[1],y[1]);

getch();

closegraph();

switch(ch)

case 1:

printf("\n enter the translation vector");

scanf("%f%f%f",&tx,&ty);

for(i=1;i<=n;i++)

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 25: Computer Graphics and Algorithms Lab Manual

x[i]=x[i]+tx;

y[i]=y[i]+ty;

break;

case 2:

printf("\n enter the scaling vector");

scanf("%f%f%f",&sx,&sy);

for(i=1;i<n;i++)

x[i]=x[i]*sx;

y[i]=y[i]*sy;

break;

case 3:

printf("\n enter the fixed point");

scanf("%d%d%d",&sx,&sy);

for(i=1;i<n;i++)

x[i]=x[i]*sx+(1-sx)*xf;

y[i]=y[i]*sy+(1-sy)*yf;

break;

case 4:

printf("\n enter the rotation angle");

scanf("%d",angle);

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 26: Computer Graphics and Algorithms Lab Manual

theta=(3.14/180)*angle;

for(i=1;i<n;i++)

x[i]=x[i]*cos(theta)+y[i]*sin(theta);

y[i]=-x[i]*sin(theta)+y[i]*cos(theta);

break;

case 5:

printf("\n enter the pilot number");

scanf("%d%d",&xr,&yr);

printf("\n enter the rotation angle");

scanf("%d",angle);

theta=(3.14/180)*(float)angle;

for(i=1;i<=n;i++)

x[i]=xr+(x[i]-xr)*cos(theta)+(y[i]-yr)*sin(theta);

y[i]=yr+(x[i]-xr)*sin(theta)+(y[i]-yr)*cos(theta);

break;

default:

exit(0);

initgraph(&gd,&gm,"");

printf("\n After transformation");

for(i=1;i<n;i++)

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 27: Computer Graphics and Algorithms Lab Manual

line(x[i],y[i],x[i+1],y[i+1]);

line(x[n],y[n],x[1],y[1]);

getch();

closegraph();

while(ch!=6);

OUTPUT:

Transformation of an Object

1. Transformation

2. Scaling

3. Scaling of a fixed point

4. Rotation

5. Rotation of a fixed pointexit

Enter your choice: 1

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 28: Computer Graphics and Algorithms Lab Manual

Enter the total no of vertices:3

Enter the co-ordinates:10 10

0 50

50 0

Enter the translation vector: 10 10

20 20

After transformation:

Transformation of an Object

1. Transformation

2. Scaling

3. Scaling of a fixed point

4. Rotation

5. Rotation of a fixed pointexit

Enter your choice: 2

Enter the total no of vertices:3

Enter the co-ordinates:10 10

0 50

50 0

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 29: Computer Graphics and Algorithms Lab Manual

Enter the scaling vector: 10 10

20 20

After transformation:

Transformation of an Object

1. Transformation

2. Scaling

3. Scaling of a fixed point

4. Rotation

5. Rotation of a fixed pointexit

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 30: Computer Graphics and Algorithms Lab Manual

Enter your choice: 3

Enter the total no of vertices:3

Enter the co-ordinates:10 10

0 50

50 0

Enter the fixed point:10 20 30

After transformation:

Transformation of an Object

1. Transformation

2. Scaling

3. Scaling of a fixed point

4. Rotation

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 31: Computer Graphics and Algorithms Lab Manual

5. Rotation of a fixed pointexit

Enter your choice: 3

Enter the total no of vertices:4

Enter the co-ordinates:10 10

0 50

50 0

Enter the rotating angle:20

After transformation:

Transformation of an Object

1. Transformation

2. Scaling

3. Scaling of a fixed point

4. Rotation

5. Rotation of a fixed pointexit

Enter your choice: 3

Enter the total no of vertices:5

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 32: Computer Graphics and Algorithms Lab Manual

Enter the co-ordinates:10 10

0 50

50 0

Enter the fixed point: 0 10

0 20

Enter the rotating angle:20

RESULT:

Thus the program for implementation of Two dimensional Transformations for Transformation, Scaling and Rotation are successfully compiled and executed.

Ex No:3 (b) REFLECTION OF AN OBJECT

Program:

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 33: Computer Graphics and Algorithms Lab Manual

#include <stdio.h>

#include<conio.h>

#include<math.h>

#include<graphics.h>

int x0=320,y0=240;

int t[3][2]=100,100,150,50,50,50;

void main()

int gd=DETECT,gm,ch;

initgraph(&gd,&gm," ");

clrscr();

do

cleardevice();

gotoxy(1,1);

printf("\t\t reflection of an object\t\t");

printf("\n1.original\n2.reflection\n3.exit");

printf("\n enter ur choice:");

scanf("%d",&ch);

if(ch==1)

cleardevice();

triangle(0,1,1,1);

getch();

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 34: Computer Graphics and Algorithms Lab Manual

if(ch==2)

reflect();

while(ch!=3);

triangle(int i,int j,int rx,int ry)

line(x0,0,x0,2*y0);

line(0,y0,2*x0,y0);

line(x0+t[0][i]*rx,y0-t[0][j]*ry,x0+t[1][i]*rx,y0-t[1][j]*ry);

line(x0+t[1][i]*rx,y0-t[1][j]*ry,x0+t[2][i]*rx,y0-t[2][j]*ry) ;

line(x0+t[2][i]*rx,y0-t[2][j]*ry,x0+t[0][i]*rx,y0-t[0][j]*ry) ;

return;

reflect()

int ch;

printf("\n 1.x ases\n 2.y axis\n 3.orgin\n4.y=x\n5.y=-x");

printf("enter ur choice");

scanf("%d",&ch);

cleardevice();

triangle(0,1,1,1);

if(ch==1)

triangle(0,1,1,-1);

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 35: Computer Graphics and Algorithms Lab Manual

if(ch==2)

triangle(0,1,-1,1);

if(ch==3)

triangle(0,1,-1,-1);

if(ch==4)

triangle(1,0,1,1);

if(ch==5)

triangle(1,0,-1,-1);

getch();

return;

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 36: Computer Graphics and Algorithms Lab Manual

OUTPUT:

Reflection of an object

Original

Reflection

Exit

Enter your choice:1

Reflection of an object

1.Original

2.Reflection

3.Exit

Enter your choice:2

x – axis

y – axis

origin

y=x

y=-x Enter ur choice : 1

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 37: Computer Graphics and Algorithms Lab Manual

Reflection of an object

1.Original

2.Reflection

3.Exit

Enter your choice:2

1.x – axis

2.y – axis

3.origin

4.y=x

5.y=-x Enter ur choice : 2

Reflection of an object

1.Original

2.Reflection

3.Exit

Enter your choice:2

1.x – axis

2.y – axis

3.origin

4.y=x

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 38: Computer Graphics and Algorithms Lab Manual

5.y=-x Enter ur choice : 3

Reflection of an object

1.Original

2.Reflection

3.Exit

Enter your choice:2

1.x – axis

2.y – axis

3.origin

4.y=x

5.y=-x Enter ur choice : 4

Reflection of an object

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 39: Computer Graphics and Algorithms Lab Manual

1.Original

2.Reflection

3.Exit

Enter your choice:2

1.x – axis

2.y – axis

3.origin

4.y=x

5.y=-x Enter ur choice : 5

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 40: Computer Graphics and Algorithms Lab Manual

RESULT:

Thus the program for implementation of Two dimensional Transformations for Reflection are successfully compiled and executed.

Ex No:3(c) SHEARING OF AN OBJECT

Program:

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

void main()

int gd=DETECT,gm,x[10],y[10],x1[10],y1[10],i,n,s,ch;

clrscr();

printf("\t\t\tSHEAR TRANSFORMATION\n");

printf("\t\t\t\-------------------");

printf("\nEnter the total number of vetices:");

scanf("\n%d",&n);

printf("\nEnter the co-ordeinates");

for(i=1;i<=n;i++)

scanf("%d%d",&x[i],&y[i]);

initgraph(&gd,&gm," ");

start:

cleardevice();

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 41: Computer Graphics and Algorithms Lab Manual

for(i=1;i<=n;i++)

x1[i]=x[i];

y1[i]=y[i];

for(i=1;i<n;i++)

line(x1[i],y1[i],x1[i+1],y1[i+1]);

line(x1[n],y1[n],x1[1],y1[1]);

gotoxy(1,1);

printf("\n1.X-SHEAR\n2.Y-SHEAR\n3.EXIT");

printf("\nEnter your choice");

switch(ch)

case 1:

gotoxy(1,5);

printf("\nEnter the shearing distance");

scanf("%d",&s);

for(i=0;i<n/2;i++)

x1[i]+=s;

break;

case 2:

gotoxy(1,5);

printf("\nEnter the shearing distance");

scanf("%d",&s);

for(i=1;i<=n/2;i++)

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 42: Computer Graphics and Algorithms Lab Manual

y1[i]+=s;

break;

case 3:

exit(0);

break;

default:

printf("\nEnter a valid choice");

getch();

goto start;

break;

for(i=1;i<n;i++)

line(x1[i],y1[i],x1[i+1],y1[i+1]);

line(x1[n],y[n],x1[1],y1[1]);

getch();

goto start;

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 43: Computer Graphics and Algorithms Lab Manual

OUTPUT:

SHEAR TRANSFORMATION

Enter the total number of Vertices: 3

Enter the co-ordinates:10 10

0 50

50 0

1.X-SHEAR

2.Y-SHEAR

3.EXIT

Enter your choice:1

Enter the shearing distance: 50

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 44: Computer Graphics and Algorithms Lab Manual

1.X-SHEAR

2.Y-SHEAR

3.EXIT

Enter your choice:2

Enter the shearing distance: 50

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 45: Computer Graphics and Algorithms Lab Manual

RESULT:

Thus the program for implementation of Two dimensional Transformations for Shearing of an object is successfully compiled and executed.

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 46: Computer Graphics and Algorithms Lab Manual

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Ex No: COHEN SUTHERLAND 2D

Page 47: Computer Graphics and Algorithms Lab Manual

DATE: LINE CLIPPING AND WINDOWING

AIM:

To study and Implement Cohen Sutherland 2D line clipping and Windowing

ALOGRITHM:

procedure CohenSutherlandLineClipAndDraw( x0,y0,x1,y1,xmin,xmax,ymin,ymax : real ; value: integer); Cohen-Sutherland clipping algorithm for line P0=(x1,y0) to P1=(x1,y1)and clip rectangle with diagonal from (xmin,ymin) to (xmax,ymax).type edge = (LEFT,RIGHT,BOTTOM,TOP); outcode = set of edge;var accept,done : boolean; outcode0,outcode1,outcodeOut : outcode; Outcodes for P0,P1, and whichever point lies outside the clip rectangle x,y : real; procedure CompOutCode(x,y: real; var code:outcode); Compute outcode for the point (x,y) begin code := []; if y > ymax then code := [TOP] else if y < ymin then code := [BOTTOM]; if x > xmax then code := code +[RIGHT] else if x < xmin then code := code +[LEFT] end;

begin accept := false; done := false; CompOutCode (x0,y0,outcode0); CompOutCode (x1,y1,outcode1); repeat if(outcode0=[]) and (outcode1=[]) then Trivial accept and exit begin accept := true; done:=true end else if (outcode0*outcode1) <> [] then done := true Logical intersection is true, so trivial reject and exit. else Failed both tests, so calculate the line segment to clip; from an outside point to an intersection with clip edge. begin At least one endpoint is outside the clip rectangle; pick it. if outcode0 <> [] then outcodeOut := outcode0 else outcodeOut := outcode1; Now find intersection point; use formulas y=y0+slope*(x-x0),x=x0+(1/slope)*(y-y0).

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 48: Computer Graphics and Algorithms Lab Manual

if TOP in outcodeOut then begin Divide line at top of clip rectangle x := x0 + (x1 - x0) * (ymax - y0) / (y1 - y0); y := ymax end if BOTTOM in outcodeOut then begin Divide line at bottom of clip rectangle x := x0 + (x1 - x0) * (ymin - y0) / (y1 - y0); y := ymax end else if RIGHT in outcodeOut then begin Divide line at right edge of clip rectangle y := y0 + (y1 - y0) * (xmax - x0) / (x1 - x0); x := xmax end else if LEFT in outcodeOut then begin Divide line at left edge of clip rectangle y := y0 + (y1 - y0) * (xmin - x0) / (x1 - x0); x := xmin end; Now we move outside point to intersection point to clip, and get ready for next pass. if (outcodeOut = outcode0) then begin x0 := x; y0 := y; CompOutCode(x0,y0,outcode0) end else begin x1 := x; y1 := y; CompOutCode(x1,y1,outcode1); end end subdivide until done; if accept then MidpointLineReal(x0,y0,x1,y1,value) Version for real coordinatesend; CohenSutherlandLineClipAndDraw

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 49: Computer Graphics and Algorithms Lab Manual

Program:

#include<stdio.h>

#include<graphics.h>

#include<conio.h>

typedef unsigned int outcode;

enum TOP=0x1, BOTTOM=0x2, RIGHT=0x4, LEFT=0x8 ;

void lineclip(x0,y0,x1,y1,xwmin,ywmin,xwmax,ywmax )

float x0,y0,x1,y1,xwmin,ywmin,xwmax,ywmax;

int gd,gm;

outcode code0,code1,codeout;

int accept = 0, done=0;

code0 = calcode(x0,y0,xwmin,ywmin,xwmax,ywmax);

code1 = calcode(x1,y1,xwmin,ywmin,xwmax,ywmax);

do

if(!(code0 | code1))

accept =1 ; done =1;

else

if(code0 & code1) done = 1;

else

float x,y;

codeout = code0 ? code0 : code1;

if(codeout & TOP)

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 50: Computer Graphics and Algorithms Lab Manual

x = x0 + (x1-x0)*(ywmax-y0)/(y1-y0);

y = ywmax;

else

if( codeout & BOTTOM)

x = x0 + (x1-x0)*(ywmin-y0)/(y1-y0);

y = ywmin;

else

if ( codeout & RIGHT)

y = y0+(y1-y0)*(xwmax-x0)/(x1-x0);

x = xwmax;

else

y = y0 + (y1-y0)*(xwmin-x0)/(x1-x0);

x = xwmin;

if( codeout == code0)

x0 = x; y0 = y;

code0=calcode(x0,y0,xwmin,ywmin,xwmax,ywmax);

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 51: Computer Graphics and Algorithms Lab Manual

else

x1 = x; y1 = y;

code1 = calcode(x1,y1,xwmin,ywmin,xwmax,ywmax);

while( done == 0);

if(accept) line(x0,y0,x1,y1);

rectangle(xwmin,ywmin,xwmax,ywmax);

getch();

int calcode (x,y,xwmin,ywmin,xwmax,ywmax)

float x,y,xwmin,ywmin,xwmax,ywmax;

int code =0;

if(y> ywmax)

code |=TOP;

else if( y<ywmin)

code |= BOTTOM;

else if(x > xwmax)

code |= RIGHT;

else if ( x< xwmin)

code |= LEFT;

return(code);

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 52: Computer Graphics and Algorithms Lab Manual

main()

float x2,y2,x1,y1,xwmin,ywmin,xwmax,ywmax;

int gd=DETECT,gm;

clrscr();

initgraph(&gd,&gm,"c:\\tc\\bgi");

printf("\n\n\tEnter the co-ordinates of Line :");

printf("\n\n\tX1 Y1 : ");

scanf("%f %f",&x1,&y1);

printf("\n\n\tX2 Y2 : ");

scanf("%f %f",&x2,&y2);

printf("\n\tEnter the co_ordinates of window :\n ");

printf("\n\txwmin , ywmin : ");

scanf("%f %f",&xwmin,&ywmin);

printf("\n\txwmax , ywmax : ");

scanf("%f %f",&xwmax,&ywmax);

clrscr();

line(x1,y1,x2,y2);

rectangle(xwmin,ywmin,xwmax,ywmax);

getch();

clrscr();

lineclip(x1,y1,x2,y2,xwmin,ywmin,xwmax,ywmax );

getch();

closegraph();

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 53: Computer Graphics and Algorithms Lab Manual

OUTPUT:Enter the C0-ordinates of line

x1,y1: 150 200x2,y2: 300 450Enter the Co-ordinates of windowxwmin,ywmin: 150 180xwmax,ywmax: 420 390Before Clipping

After Clipping

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 54: Computer Graphics and Algorithms Lab Manual

RESULT:

Thus the program for implementation of Cohen Sutherland 2-D Line, Clipping and Windowing are successfully compiled and executed.

DATE:

AIM: To study and implement Sutherland – Hodgeman polygon clipping using TC.

ALGORITHM:

type vertex = point; point hold real x,y edge = array[1..2] of vertex; vertexArray = array[1..MAX] of vertex; MAX is a declared constant

procedure SutherlandHodgmanPolygoClip ( inVertexArray : vertexArray; Input vertex array var outVertexArray : vertexArray; Output vertex array inLength : integer; Number of entries in inVertexArray var outLength : integer; Number of entries in outVertexArray clipBoundary : edge); Edge of clip polygonvar s,p, Start, end point of current polygon edge i : vertex; Intersection point with a clip boundary j : integer; Vertex loop counter

procedure Output( newVertex : vertex; var outLength : integer; var outVertexArray : vertexArray); Adds newVertex to outVertexArray and then updates outLength begin ... end;

function Inside(testVertex : vertex; clipBoundary : edge):boolean; Checks whether the vertex lies inside the clip edge or not begin

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

EX NO. SUTHERLAND – HODGEMAN POLYGON CLIPPING

Page 55: Computer Graphics and Algorithms Lab Manual

... end;

procedure Intersect(first,second:vertex; clipBoundary:edge; var intersectPt:vertex); Clips polygon edge (first,second) against clipBoundary, outputs the new point begin ... end;

begin outLength := 0; s := inVertexArray[inLength]; Start with the last vertex in inVertexArray for j := 1 to inLength do begin p := inVertexArray[j]; Now s and p correspond to the vertices in Fig. 3.48 if Inside(p,clipBoundary) then Cases 1 and 4 if Inside(s, clipBoundary) then Output(p, outLength, outVertexArray) Case 1 else begin Intersect(s, p, clipBoundary, i); Output(i, outLength, outVertexArray); Output(p, outLength, outVertexArray) end else Cases 2 and 3 if Inside(s, clipBoundary) then Cases 2 begin Intersect(s, p, clipBoundary, i); Output(i, outLength, outVertexArray) end; No action for case 3 s := p Advance to next pair of vertices end forend; SutherlandHodgmanPolygonClip

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 56: Computer Graphics and Algorithms Lab Manual

Program:

#include<iostream.h>

#include<graphics.h>

#include<conio.h>

#define round(a)((int)(a+0.5))

int k;

float xmin,ymin,xmax,ymax,arr[20],m;

void clipl(float x1,float y1,float x2,float y2)

if(x2-x1)

m=(y2-y1)/(x2-x1);

else

m=100000;

if(x1>=xmin && x2>=xmin)

arr[k]=x2;

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 57: Computer Graphics and Algorithms Lab Manual

arr[k+1]=y2;

k+=2;

if(x1<xmin && x2>=xmin)

arr[k]=xmin;

arr[k+1]=y1+m*(xmin-x1);

arr[k+2]=x2;

arr[k+3]=y2;

k+=4;

if(x1>=xmin && x2<xmin)

arr[k]=xmin;

arr[k+1]=y1+m*(xmin-x1);

k+=2;

void clipt(float x1,float y1,float x2,float y2)

if(y2-y1)

m=(x2-x1)/(y2-y1);

else

m=100000;

if(y1<=ymax && y2<=ymax)

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 58: Computer Graphics and Algorithms Lab Manual

arr[k]=x2;

arr[k+1]=y2;

k+=2;

if(y1>ymax && y2<=ymax)

arr[k]=x1+m*(ymax-y1);

arr[k+1]=ymax;

arr[k+2]=x2;

arr[k+3]=y2;

k+=4;

if(y1<=ymax && y2>ymax)

arr[k]=x1+m*(ymax-y1);

arr[k+1]=ymax;

k+=2;

void clipr(float x1,float y1,float x2,float y2)

if(x2-x1)

m=(y2-y1)/(x2-x1);

else

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 59: Computer Graphics and Algorithms Lab Manual

m=100000;

if(x1<=xmax && x2<=xmax)

arr[k]=x2;

arr[k+1]=y2;

k+=2;

if(x1>xmax && x2<=xmax)

arr[k]=xmax;

arr[k+1]=y1+m*(xmax-x1);

arr[k+2]=x2;

arr[k+3]=y2;

k+=4;

if(x1<=xmax && x2>xmax)

arr[k]=xmax;

arr[k+1]=y1+m*(xmax-x1);

k+=2;

void clipb(float x1,float y1,float x2,float y2)

if(y2-y1)

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 60: Computer Graphics and Algorithms Lab Manual

m=(x2-x1)/(y2-y1);

else

m=100000;

if(y1>=ymin && y2>=ymin)

arr[k]=x2;

arr[k+1]=y2;

k+=2;

if(y1<ymin && y2>=ymin)

arr[k]=x1+m*(ymin-y1);

arr[k+1]=ymin;

arr[k+2]=x2;

arr[k+3]=y2;

k+=4;

if(y1>=ymin && y2<ymin)

arr[k]=x1+m*(ymin-y1);

arr[k+1]=ymin;

k+=2;

void main()

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 61: Computer Graphics and Algorithms Lab Manual

int gdriver=DETECT,gmode;

int n,poly[20];

float xi,yi,xf,yf,polyy[20];

clrscr();

cout<<" Coordinates of rectangular clip window :\n xmin,ymin :";

cin>>xmin>>ymin;

cout<<"xmax,ymax :";

cin>>xmax>>ymax;

cout<<"\n\n Polygon to be clipped: \n No of sides :";

cin>>n;

cout<<"Enter the coordinates:";

for(int i=0;i<2*n;i++)

cin>>polyy[i];

polyy[i]=polyy[0];

poly[i+1]=polyy[1];

for(i=0;i<2*n+2;i++)

poly[i]=round(polyy[i]);

initgraph(&gdriver,&gmode,"c:\\tc\\bgi");

setcolor(RED);

rectangle(xmin,ymax,xmax,ymin);

cout<<"\t\t UNCLIPPED POLYGON";

setcolor(WHITE);

fillpoly(n,poly);

getch();

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 62: Computer Graphics and Algorithms Lab Manual

cleardevice();

k=0;

for(i=0;i<2*n;i+=2)

clipl(polyy[i],polyy[i+1],polyy[i+2],polyy[i+3]);

n=k/2;

for(i=0;i<k;i++)

polyy[i]=arr[i];

polyy[i]=polyy[0];

polyy[i+1]=polyy[1];

k=0;

for(i=0;i<2*n;i+=2)

clipt(polyy[i],polyy[i+1],polyy[i+2],polyy[i+3]);

n=k/2;

for(i=0;i<k;i++)

polyy[i]=arr[i];

polyy[i]=polyy[0];

polyy[i+1]=polyy[1];

k=0;

for(i=0;i<2*n;i+=2)

clipr(polyy[i],polyy[i+1],polyy[i+2],polyy[i+3]);

n=k/2;

for(i=0;i<k;i++)

polyy[i]=arr[i];

polyy[i]=polyy[0];

polyy[i+1]=polyy[1];

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 63: Computer Graphics and Algorithms Lab Manual

k=0;

for(i=0;i<2*n;i+=2)

clipb(polyy[i],polyy[i+1],polyy[i+2],polyy[i+3]);

for(i=0;i<k;i++)

poly[i]=round(arr[i]);

if(k)

fillpoly(k/2,poly);

setcolor(RED);

rectangle(xmin,ymax,xmax,ymin);

cout<<"\t CLIPPED POLYGON";

getch();

closegraph();

OUTPUT:

Co ordinates of regular clip window:

Xmin,ymin:150 180

Xmax,ymax:200 260

Polygon to be clipped:

No of sides:4

Enter the co-ordinates:10 20

30 45

50 60

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 64: Computer Graphics and Algorithms Lab Manual

70 80

Unclipped Window:

Clipped Window:

RESULT:

Thus the program for implementation of Sutherland Hodgeman Polygon Clipping is successfully compiled and executed.

DATE: TRANSLATION, ROTATION, SCALING

AIM: To study and Implement 3D Transformation

ALGORITHM:

STEP 1:Start the program

STEP 2:Include the required variables and the graphics mode specifying the path.STEP 3:Get the vertices and get the coordinates in each case.STEP 4:Get the options then using the suited case to follow transformation.STEP 5:If the option1 get the tx ,ty and tz coordinate then perform the translation operation.

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Ex No: THREE DIMENSIONAL TRANSFORMATIONS

Page 65: Computer Graphics and Algorithms Lab Manual

STEP 6:Repeat the operation for all the coordinates.STEP 7:If option2 get the sx ,sy and sz coordinates then perform the scaling operation

STEP 8:Repeat the operation for all coordinates.STEP 9:Display the output result. If the option is 3 get the rotation angle(r) then perform the rotation operation and find the r1=r1*(3.14)/(180)

STEP 10.To perform rotation use switch case,case1 for x direction rotation,case 2 for y direction rotation and case 3 for z direction rotation ,case 4 for exit operation. In x direction rotation, perform the operation

In y direction rotation, perform the operation

In z direction rotation, perform the operation

STEP 11. Display the output resultSTEP 12:If option 4 exit the programSTEP 13:Stop the program.

PROGRAM:

#include<stdio.h>

#include<conio.h>

#include<graphics.h>

#include<math.h>

int maxx,maxy,midx,midy;

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 66: Computer Graphics and Algorithms Lab Manual

void axis()

getch();

cleardevice();

line(midx,0,midx,maxy);

line(0,midy,maxx,midy);

void main()

int gd,gm,x,y,z,o,x1,x2,y1,y2;

detectgraph(&gd,&gm);

initgraph(&gd,&gm,"d:\\tc\\bgi");

setfillstyle(0,getmaxcolor());

maxx=getmaxx();

maxy=getmaxy();

midx=maxx/2;

midy=maxy/2;

axis();

bar3d(midx+100,midy-150,midx+60,midy-100,10,1);

printf("\Enter the translation factor");

scanf("%d%d",&x,&y);

axis();

printf("After translation");

bar3d(midx+100,midy-150,midx+60,midy-100,10,1);

bar3d(midx+x+100,midy-(y+150),midx+x+60,midy-(y+100),10,1);

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 67: Computer Graphics and Algorithms Lab Manual

axis();

bar3d(midx+100,midy-150,midx+60,midy-100,10,1);

printf("Enter the scaling factor");

scanf("%d%d%d",&x,&y,&z);

axis();

printf("After scaling");

bar3d(midx+100,midy-150,midx+60,midy-100,10,1);

bar3d(midx+(x*100),midy-(y*150),midx+(x*60),midy-(y*100),10*z,1);

axis();

bar3d(midx+100,midy-150,midx+60,midy-100,10,1);

printf("Enter the rotation angle");

scanf("%d",&o);

x1=50*cos(o*3.14/180)-100*sin(o*3.14/180);

y1=50*sin(o*3.14/180)+100*cos(o*3.14/180);

x2=60*cos(o*3.14/180)-90*sin(o*3.14/180);

y2=60*sin(o*3.14/180)+90*cos(o*3.14/180);

axis();

printf("After rotating about Z-axis");

bar3d(midx+100,midy-150,midx+60,midy-100,10,1);

bar3d(midx+x1,midy-y1,midx+x2,midy-y2,10,1);

axis();

printf("After rotating about x-axis");

bar3d(midx+100,midy-150,midx+60,midy-100,10,1);

bar3d(midx+100,midy-x1,midx+60,midy-x2,10,1);

axis();

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 68: Computer Graphics and Algorithms Lab Manual

printf("After rotating about Y-axis");

bar3d(midx+100,midy-150,midx+60,midy-100,10,1);

bar3d(midx+x1,midy-150,midx+x2,midy-100,10,1);

getch();

closegraph();

OUTPUT:

Enter the translation factor: 10 10 10 10

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 69: Computer Graphics and Algorithms Lab Manual

After translation:

Enter scaling factor: 10 20 30

After scaling:

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 70: Computer Graphics and Algorithms Lab Manual

Enter rotation angle: 20

After Rotaion about z-axis:

After Rotaion about x-axis:

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 71: Computer Graphics and Algorithms Lab Manual

After Rotaion about y-axis:

RESULT:

Thus the program for implementation of Three Dimensional transformations, Scaling and Rotation are successfully compiled and executed.

SRIRAM ENGINEERING COLLEGE PERUMALPATTU-602024

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 72: Computer Graphics and Algorithms Lab Manual

divide & conquer method.

Aim: Write a program for finding the maximum & minimum using divide & conquer method.

Theory: Divide­and­Conquer Algorithms: These algorithms have the following outline: To solve a problem, divide it into sub problems. Recursively solve the sub problems. Finally glue the resulting solutions together to obtain the solution to the original problem. Progress here is measured by how much smaller the sub problems are compared to the original problem.

Finding Maximum/minimum numbers in a list: Suppose we wish to find the minimum and maximum items in a list of numbers. How many comparisons does it take?

Algorithm StraightMaxMin(a,n,max,min)

max=min=a[1]; for i=2 to n do

if (a[i]>max) then max = a[i]; if (a[i]<min) then min = a[i];

Let us analyze the number of comparisons made for finding the maximum. It can be seen that the complexity will be proportional to the number of comparisons. To find the maximum, we see from the for­loop that N–1 comparisons will be made. The algorithm for finding the minimum follows in a similar way. If we find the minimum after finding the maximum, it is enough to find the minimum among the remaining N–1 numbers (assuming there are at least 2 numbers; otherwise, maximum and minimum will be the same). So to find the maximum and minimum of N numbers, we need (N–1) + (N–2) = 2N –3 comparisons. Now, let us see whether we can develop an algorithm whose complexity is better than that of solution 1 using the divide–and–conquer method.

This will be the basic principle of the algorithm to find the maximum and minimum of an array of numbers. The main idea of using the divide–and–conquer strategy is described below:

Ø Divide array A into two sub­parts A1 and A2 such that A1 and A2 together form A.

Ø Find the maximum and minimum of each by recursive application of the algorithm.

Ø The maximum and minimum of A can be computed from the maximum and minimum of A1 and A2 by making two comparisons.

Program for finding the maximum & minimum using

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 73: Computer Graphics and Algorithms Lab Manual

AlgorithmMINMAX (A, L, U, mx, mn); ( A is an array ranging between L and U; mx and mn will have the maximum and minimum value respectively when the procedure terminates ) var l1 , l2 , U1,U2: integer ; ( Local Variables ) mx1,mx2,mn1,mn2: integer ; (Local Variables )

If (U == L) then max=min=a[L]; else If (U– L+1) = 2 then

if A[L] > A[U] then mx:= A[L]; ( maximum ) mn:= A[U]; ( minimum )

else mx:= A[U]; ( maximum ) mn:= A[L]; ( minimum )

else

// Split A into two halves A1 and A2 with lower and upper indices to be l1 , U1 and l2 , U2 respectively;

call MINMAX (A, l1 , U1 , mx1 , mn1 ); call MINMAX (A, l2, U2, mx2, mn2); mx :=maximum (mx1 , mx2 ); (maximum returns the maximum of the two

values) mn := minimum (mn1 , mn2 ); (minimum returns the minimum of the two

values)

Input: 22 13 ­5 ­8 15 60 17 31 47

Output: Maximum: 60 Minimum : ­8

Conclusion: Thus we saw using StraightMaxMin algorithm, we need (N–1) + (N–2) = 2N –3 comparisons. If we solve the same problem using divide and conquer technique number of comparisons are reduced to 3n/2 – 2. This saves 25% comparisons.

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 74: Computer Graphics and Algorithms Lab Manual

method.

Aim: Write a program to implement knapsack problem using greedy method.

Theory: Greedy algorithms are simple and straightforward. They are shortsighted in their approach in the sense that they take decisions on the basis of information at hand without worrying about the effect these decisions may have in the future. They are easy to invent, easy to implement and most of the time quite efficient. Many problems cannot be solved correctly by greedy approach. Greedy algorithms are used to solve optimization problems

Greedy Approach

Greedy Algorithm works by making the decision that seems most promising at any moment; it never reconsiders this decision, whatever situation may arise later.

As an example consider the problem of "Making Change".

Coins available are: • dollars (100 cents) • quarters (25 cents) • dimes (10 cents) • nickels (5 cents) • pennies (1 cent)

Problem Make a change of a given amount using the smallest possible number of coins.

Informal Algorithm • Start with nothing. • at every stage without passing the given amount.

o add the largest to the coins already chosen.

Example Make a change for 2.89 (289 cents) here n = 2.89 and the solution contains 2 dollars (200 cents) 3 quarters (75 cents), 1 dime (10 cents) and 4 pennies (4 cents). The algorithm is greedy because at every stage it chooses the largest coin without worrying about the consequences. Moreover, it never changes its mind in the sense that once a coin has been included in the solution set, it remains there.

To construct the solution in an optimal way. Algorithm maintains two sets. One contains chosen items and the other contains rejected items.

The greedy algorithm consists of four (4) function.

1. A function that checks whether chosen set of items provide a solution. 2. A function that checks the feasibility of a set.

Program to implement knapsack problem using greedy

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 75: Computer Graphics and Algorithms Lab Manual

3. The selection function tells which of the candidates is the most promising. 4. An objective function, which does not appear explicitly, gives the value of a

solution.

Structure Greedy Algorithm

• Initially the set of chosen items is empty i.e., solution set.

• At each step

o item will be added in a solution set by using selection function.

o IF the set would no longer be feasible

§ reject items under consideration (and is never consider again).

o ELSE IF set is still feasible THEN

§ add the current item.

Definitions of feasibility

A feasible set (of candidates) is promising if it can be extended to produce not merely a solution, but an optimal solution to the problem. In particular, the empty set is always promising why? (because an optimal solution always exists)

A greedy strategy usually progresses in a top­down fashion, making one greedy choice after another, reducing each problem to a smaller one.

Greedy­Choice Property The "greedy­choice property" and "optimal substructure" are two ingredients in the problem that lend to a greedy strategy.

Greedy­Choice Property It says that a globally optimal solution can be arrived at by making a locally optimal choice.

Knapsack Problem Statement We are given n objects and a knapsack or bag. Object i has a weight wi and the knapsack has a capacity m.

There are two versions of problem

I. Fractional knapsack problem

The setup is same, we can take fractions of items, meaning that the items can be broken into smaller pieces so that we may decide to carry only a fraction of xi of item i, where 0 ≤ xi ≤ 1. If a fraction xi of object i is placed into the knapsack, then a profit pi xi is earned.

The objective is to obtain a filling of the knapsack that maximizes the total profit earned.

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 76: Computer Graphics and Algorithms Lab Manual

The idea is to calculate for each object the ratio of value/cost, and sort them according to this ratio. Then you take the objects with the highest ratios and add them until you can’t add the next object as whole. Finally add as much as you can of the next object.

So, for our example: v(weight) = 4, 2, 2, 1, 10 c(profit) = 12, 1, 2, 1, 4 r = 1/3, 2, 1, 1, 5/2

From this it’s obvious that you should add the objects: 5, 2, 3, and 4 and then as much as possible of 1. We can choose objects like this:

Added object 5 (10$, 4Kg) completely in the bag. Space left: 11. Added object 2 (2$, 1Kg) completely in the bag. Space left: 10. Added object 3 (2$, 2Kg) completely in the bag. Space left: 8. Added object 4 (1$, 1Kg) completely in the bag. Space left: 7. Added 58% (4$, 12Kg) of object 1 in the bag. Filled the bag with objects worth 15.48$.

II. 0­1 knapsack problem

The setup is the same, but the items may not be broken into smaller pieces, so we may decide either to take an item or to leave it (binary choice), but may not take a fraction of an item.

Algorithm fractional­knapsack (w, v, W)

for i =1 to n do x[i] =0

weight = 0 while weight < W do i = best remaining item if weight + w[i] ≤ W then x[i] = 1 weight = weight + w[i]

else x[i] = (w ­ weight) / w[i] weight = W

return x

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 77: Computer Graphics and Algorithms Lab Manual

Program Snippets:

int n = 5; /* The number of objects */ int c[10] = 12, 1, 2, 1, 4; /* c[i] is the *COST* of the ith object;

i.e. what YOU PAY to take the object */ int v[10] = 4, 2, 2, 1, 10; /* v[i] is the *VALUE* of the ith object;

i.e.what YOU GET for taking the object */ int W = 15; /* The maximum weight you can take */ void simple_fill()

int cur_w; float tot_v; int i, maxi; int used[10];

for (i = 0; i < n; ++i) used[i] = 0; /* Not used the ith object yet */

cur_w = W; while (cur_w > 0) /* while there's still room*/ /* Find the best object */ maxi = ­1; for (i = 0; i < n; ++i) if ((used[i] == 0) &&((maxi == ­1) || ((float)v[i]/c[i] >

(float)v[maxi]/c[maxi]))) maxi = i;

used[maxi] = 1; /* mark the maxi­th object as used */ cur_w ­= c[maxi]; /* with the object in the bag, I can carry less */ tot_v += v[maxi]; if (cur_w >= 0)

printf("Added object %d (%d$, %dKg) completly in the bag. Space left: %d.\n", maxi + 1, v[maxi], c[maxi], cur_w);

else printf("Added %d%% (%d$, %dKg) of object %d in the bag.\n", (int)((1

+ (float)cur_w/c[maxi]) * 100), v[maxi], c[maxi], maxi + 1); tot_v ­= v[maxi]; tot_v += (1 + (float)cur_w/c[maxi]) * v[maxi];

printf("Filled the bag with objects worth %.2f$.\n", tot_v);

Output:

Added object 5 (10$, 4Kg) completely in the bag. Space left: 11. Added object 2 (2$, 1Kg) completely in the bag. Space left: 10. Added object 3 (2$, 2Kg) completely in the bag. Space left: 8. Added object 4 (1$, 1Kg) completely in the bag. Space left: 7. Added 58% (4$, 12Kg) of object 1 in the bag. Filled the bag with objects worth 15.48$.

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 78: Computer Graphics and Algorithms Lab Manual

Conclusion:

Performance Analysis

If the items are already sorted into decreasing order of vi / wi, then the while­loop takes a time in O(n); Therefore, the total time including the sort is in O(n log n). If we keep the items in heap with largest vi/wi at the root. Then

• creating the heap takes O(n) time • while­loop now takes O(log n) time (since heap property must be restored after

the removal of root)

Although this data structure does not alter the worst­case, it may be faster if only a small number of items are needed to fill the knapsack.

One variant of the 0­1 knapsack problem is when order of items are sorted by increasing weight is the same as their order when sorted by decreasing value. The optimal solution to this problem is to sort by the value of the item in decreasing order. Then pick up the most valuable item which also has a least weight. First, if its weight is less than the total weight that can be carried. Then deduct the total weight that can be carried by the weight of the item just pick. The second item to pick is the most valuable item among those remaining. Keep follow the same strategy until we cannot carry more item (due to weight).

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 79: Computer Graphics and Algorithms Lab Manual

method.

Aim: Write a program for finding minimum cost spanning tree using greedy method.

Theory:

A spanning tree of a graph is any tree that includes every vertex in the graph. Little more formally, a spanning tree of a graph G is a sub graph of G that is a tree and contains all the vertices of G. An edge of a spanning tree is called a branch; an edge in the graph that is not in the spanning tree is called a chord. We construct spanning tree whenever we want to find a simple, cheap and yet efficient way to connect a set of terminals (computers, cites, factories, etc.). Spanning trees are important because of following reasons.

• Spanning trees construct a sparse sub graph that tells a lot about the original graph.

• Spanning trees a very important in designing efficient routing algorithms. • Some hard problems (e.g., Steiner tree problem and traveling salesman problem)

can be solved approximately by using spanning trees. • Spanning trees have wide applications in many areas, such as network design, etc.

Here are some examples:

A graph G: Three (of the many possible) spanning trees from graph G:

A weighted graph G: The minimum spanning tree from weighted graph G:

Figure 6.1: Graph G and its spanning trees To explain further upon the Minimum Spanning Tree (MST), and what it applies to, let's consider a couple of real­world examples:

Program for finding minimum cost spanning tree using greedy

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 80: Computer Graphics and Algorithms Lab Manual

1. One practical application of a MST would be in the design of a network. For instance, a group of individuals, who are separated by varying distances, wish to be connected together in a telephone network. Although MST cannot do anything about the distance from one connection to another, it can be used to determine the least costly paths with no cycles in this network, thereby connecting everyone at a minimum cost.

2. Another useful application of MST would be finding airline routes. The vertices of the graph would represent cities, and the edges would represent routes between the cities. Obviously, the further one has to travel, the more it will cost, so MST can be applied to optimize airline routes by finding the least costly paths with no cycles.

To explain how to find a Minimum Spanning Tree, we will look at two algorithms: the Kruskal algorithm and the Prim algorithm. Both algorithms differ in their methodology, but both eventually end up with the MST. Kruskal'’s algorithm uses edges, and Prim’s algorithm uses vertex connections in determining the MST.

Kruskal's Algorithm:

This is a greedy algorithm. A greedy algorithm chooses some local optimum (ie. picking an edge with the least weight in a MST).

Kruskal'’s algorithm works as follows: Take a graph with 'n' vertices, keep adding the shortest (least cost) edge, while avoiding the creation of cycles, until (n ­ 1) edges have been added. (NOTE: Sometimes two or more edges may have the same cost. The order in which the edges are chosen, in this case, does not matter. Different MSTs may result, but they will all have the same total cost, which will always be the minimum cost)

Algorithm KruskalMST Input: A weighted, connected and undirected graph G = (V,E). Output: A minimal spanning tree of G. Step 1: φ = T . Step 2: while T contains less than n­1edges do

Choose an edge (v,w) from E of the smallest weight. Delete (v,w) from E. If the adding of (v,w)does not create cycle in T then

Add (v,w) to T. Else Discard (v,w).

end while

Prim's Algorithm:

This algorithm builds the MST one vertex at a time. It starts at any vertex in a graph (vertex A, for example), and finds the least cost vertex (vertex B, for example) connected to the start vertex. Now, from either 'A' or 'B', it will find the next least costly vertex connection, without creating a cycle (vertex C, for example). Now, from either 'A', 'B', or 'C', it will find the next least costly vertex connection, without creating a cycle, and so on it goes. Eventually, all the vertices will be connected, without any cycles, and an MST will be the result. (NOTE: Two or more edges may have the same cost, so when there is a

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 81: Computer Graphics and Algorithms Lab Manual

choice by two or more vertices that is exactly the same, then one will be chosen, and an MST will still result)

Some important facts about spanning trees are as follows:

• Any two vertices in a tree are connected by a unique path. • Let T be a spanning tree of a graph G, and let e be an edge

of G not in T. The T+e contain a unique cycle.

Greediness: It is easy to see that this algorithm has the property that each edge is examined at most once. Algorithms, like this one, which examine each entity at most once and decide its fate once and for all during that examination, are called greedy algorithms. The obvious advantage of greedy approach is that we do not have to spend time reexamining entities.

Figure 6.2: Graph G

Applying Kruskal's Algorithm on the graph shown in figure 6.2

Using the above graph, here are the steps to the MST, using Kruskal's Algorithm:

1. N1 to N2 ­ cost is 1 ­ add to tree 2. N7 to N8 ­ cost is 1 ­ add to tree 3. N2 to N3 ­ cost is 2 ­ add to tree 4. N1 to N6 ­ cost is 3 ­ add to tree 5. N2 to N6 ­ cost is 4 ­ reject because it forms a circuit 6. N3 to N4 ­ cost is 4 ­ add to tree 7. N2 to N7 ­ cost is 5 ­ add to tree 8. N3 to N7 ­ cost is 6 ­ reject because it forms a circuit 9. N4 to N8 ­ cost is 6 ­ reject because it forms a circuit 10. N4 to N7 ­ cost is 7 ­ reject because it forms a circuit 11. N4 to N5 ­ cost is 7 ­ add to tree

We stop here, because n ­1 edges have been added. We are left with the minimum spanning tree, with a total weight of 23.

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 82: Computer Graphics and Algorithms Lab Manual

Program Snippets:

#define N 6 /* number of vertices */ #define M 15 /* number of edges in graph */

int U[N]; /* function prototypes */ void makeset (int i); int find (int i); void merge (int p, int q); int equal (int p, int q); void initial (int n); void test_univ (void); void pause (void); /* used mainly for test purposes */

/* function definitions */ int main() int W[N][N] = 0,2,4,1,3,2, /* weighted graph */

2,0,6,4,5,1, 4,6,0,4,2,1, 1,4,4,0,5,4, 3,5,2,5,0,6, 2,1,1,4,6,0;

int E[M][3]; /* complete set of edges */ int F[N­1][3]; /* set of edges in min. span. tree */ int num_edges = 0; /* num of edges in min. span. tree */ int next_edge = 0; /* next edge not yet considered */ int weight = 0; /* minimal spanning tree weight */ int a, b, c, i, j, k; /* counter/placeholder variables */

/* initialize set of edges */ k = 0; for (i = 0; i < N; i++) for (j = 0; j < N; j++) if (j > i) E[k][0] = i; /* first vertex of edge */ E[k][1] = j; /* second vertex of edge */ E[k][2] = W[i][j]; /* weight of edge */ k++;

/* display set of edges ­ before sort */ for (i = 0; i < M; i++) for (j = 0; j < 3; j++)

printf(" %3d", E[i][j]); printf("\n");

pause();

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 83: Computer Graphics and Algorithms Lab Manual

/* sort set of edges in non­decreasing order by weight ­ bubblesort */

for (i = M ­ 1; i > 0; i­­) for (j = 0; j < i; j++) if (E[j][2] > E[j+1][2]) a = E[j][0]; b = E[j][1]; c = E[j][2]; E[j][0] = E[j+1][0]; E[j][1] = E[j+1][1]; E[j][2] = E[j+1][2]; E[j+1][0] = a; E[j+1][1] = b; E[j+1][2] = c;

/* display set of edges ­ after sort */ for (i = 0; i < M; i++) for (j = 0; j < 3; j++)

printf(" %3d", E[i][j]); printf("\n");

/* create n disjoint subsets */ initial (N);

/* initialize set of edges in min. span. tree to empty */ for (i = 0; i < N ­ 1; i++) for (j = 0; j < 3; j++) F[i][j] = ­1; /* '­1' denotes 'empty' */

test_univ();

/* find minimal spanning tree */ while (num_edges < N ­ 1) a = E[next_edge][0]; b = E[next_edge][1];

i = find(a); j = find(b);

if (!equal(i, j)) merge (i, j); F[num_edges][0] = E[next_edge][0]; F[num_edges][1] = E[next_edge][1]; F[num_edges][2] = E[next_edge][2]; num_edges++;

test_univ();

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 84: Computer Graphics and Algorithms Lab Manual

next_edge++;

/* display edges comprising minimal spanning tree */ printf("\nMinimal Spanning Tree Edges:\n"); printf("F = ("); for (i = 0; i < N ­ 1; i++) printf("(V%d,V%d)", F[i][0], F[i][1]); if (i < N ­ 2) printf(", ");

weight = weight + F[i][2]; printf(")\n"); printf("Minimal Spanning Tree Weight = %d\n", weight);

return (0);

/*************** makeset() ***************/ void makeset (int i) U[i] = i;

/*************** find() ***************/ int find (int i) int j;

j = i; while (U[j] != j) j = U[j];

return (j);

/*************** merge() ***************/ void merge (int p, int q) if (p < q)

U[q] = p; else U[p] = q;

/*************** equal() ***************/ int equal (int p, int q) if (p == q)

return (1); else return (0);

/*************** initial() ***************/ void initial (int n)

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 85: Computer Graphics and Algorithms Lab Manual

int i;

for (i = 0; i < n; i++) makeset(i);

/*************** test() ***************/ void test_univ (void) /* test universe values */ int i;

printf("\nThe disjoint subsets are:\n"); for (i = 0; i < N; i++) printf(" %3d", U[i]);

printf("\n");

/*************** pause() ***************/ void pause (void) int i;

printf("Press ENTER to continue...\n"); i = getchar();

Conclusion:

Performance analysis of Kruskal’s algorithm:

• Creation of the priority queue

If there are e edges, it is easy to see that it takes O(elog e) time to insert the edges into a partially ordered tree

• Each deletemin operation takes O(log e) time in the worst case. Thus finding and deleting least­cost edges, over the while iterations contribute O(log e) in the worst case.

• The total time for performing all the merge and find is : O(elog e) .

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 86: Computer Graphics and Algorithms Lab Manual

using dynamic programming.

Aim: Write a program to implement traveling salesperson problem using dynamic programming.

Theory:

The Traveling Salesman Problem (TSP) is a deceptively simple combinatorial problem. It can be stated very simply:

A salesman spends his time visiting n cities (or nodes) cyclically. In one tour he visits each city just once, and finishes up where he started. In what order should he visit them to minimize the distance traveled?

Many TSP's are symmetric ­ that is, for any two cities A and B, the distance from A to B is the same as that from B to A. In this case you will get exactly the same tour length if you reverse the order in which they are visited ­ so there is no need to distinguish between a tour and its reverse, and you can leave off the arrows on the tour diagram.

If there are only 2 cities then the problem is trivial, since only one tour is possible. For the symmetric case a 3 city TSP is also trivial. If all links are present then there are (n­1)! Different tours for an n city asymmetric TSP. To see why this is so, pick any city as the first ­ then there are n­1 choices for the second city visited, n­2 choices for the third, and so on. For the symmetric case there are half as many distinct solutions ­ (n­1)!/2 for an n city TSP. In either case the number of solutions becomes extremely large for large n, so that an exhaustive search is impractical.

Figure 8.1 Graph G

For the graph G shown in figure 8.1, distance matrix: D = 0 2 9 10,

1 0 6 4, 15 7 0 8, 6 3 12 0

Let g(i,S) be the length of shortest path starting at vertex i, going through all vertices in S, and terminating at vertex 1.

g(2,ø) = c21 = 1 g(3, ø) = c31 = 15 g(4, ø) = c41 = 6

1

4

2

3

Program to implement traveling salesperson problem

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 87: Computer Graphics and Algorithms Lab Manual

k = 1, consider sets of 1 element:

Set 2: g(3,2) = c32 + g(2, ø) = c32 + c21 = 7 + 1 = 8 p(3,2) = 2 g(4,2) = c42 + g(2, ø) = c42 + c21 = 3 + 1 = 4 p(4,2) = 2

Set 3: g(2,3) = c23 + g(3, ø) = c23 + c31 = 6 + 15 = 21 p(2,3) = 3 g(4,3) = c43 + g(3, ø) = c43 + c31 = 12 + 15 = 27 p(4,3) = 3

Set 4: g(2,4) = c24 + g(4, ø) = c24 + c41 = 4 + 6 = 10 p(2,4) = 4 g(3,4) = c34 + g(4, ø) = c34 + c41 = 8 + 6 = 14 p(3,4) = 4

k = 2, consider sets of 2 elements:

Set 2,3: g(4,2,3) = min c42 + g(2,3), c43 + g(3,2) = min 3+21, 12+8= min 24, 20= 20 p(4,2,3 = 3

Set 2,4: g(3,2,4) = min c32 + g(2,4), c34 + g(4,2) = min 7+10, 8+4= min 17, 12 = 12 p(3,2,4 = 4

Set 3,4: g(2,3,4) = min c23 + g(3,4), c24 + g(4,3) = min 6+14, 4+27= min 20, 31= 20 p(2,3,4 = 3

Length of an optimal tour: f = g(1,2,3,4) = min c12 + g(2,3,4), c13 + g(3,2,4), c14 + g(4,2,3) = min 2 + 20, 9 + 12, 10 + 20 = min 22, 21, 30 = 21 Successor of node 1: p(1,2,3,4) = 3 Successor of node 3: p(3, 2,4) = 4 Successor of node 4: p(4, 2) = 2 Optimal TSP tour: 1 3 4 2 1

Algorithm TSP

Input :Number of cities n and array of costs c(i,j) i,j=1,..n (We begin from city number 1) Output:Vector of cities and total cost.

(* starting values *) C=0 cost=0 visits=0 e=1 (*e=pointer of the visited city) (* determination of round and cost) for r=1 to n­1 do

choose of pointer j with minimum=c(e,j)=minc(e,k);visits(k)=0 and k=1,..,n cost=cost+minimum e=j C(r)=j

end r­loop C(n)=1 cost=cost+c(e,1)

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 88: Computer Graphics and Algorithms Lab Manual

Program Snippets:

void travel(int n, const number W [] [],index P [] [], number & minlength) index i, j, k; number D [1 .. n] [subset of V ­ v1];

for (i = 2; i <= n; i++) D [i] [⊘] = W[i] [1];

for (k = 1; k <= n ­ 2; k++) for (all subsets A V ­ v1 V ­ v1 containing k vertices)

for(i such that i ≠ 1 and vi is not in A) D [i] [A] = minimum (W [i] [j] + D [j] [A ­ vj]);

j: [vj ∊ A P[i] [A] = value of j that gave the minimum;

D [1] [V ­ v1] = minimum (W[1] [j] + D[j] [V ­ v1, vj]);

2 ≤ j ≤ n P[1] [V ­ v1] = value of j that gave the minimum; minlength = D[1] [V ­ v1];

Conclusion:

• Time complexity – Let N be the number of g(i,S) that have to be computed

N =

– Total time = O(n 2 2 n ) – This is better than enumerating all n! different tours

2 2

0 2 ) 1 (

2 ) 1 ( −

=

− =

− − ∑ n

n

k n

k n

n

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 89: Computer Graphics and Algorithms Lab Manual

dynamic programming.

Aim: Write a program to find shortest path for multistage graph using dynamic programming.

Theory:

Definition: multistage graph G(V,E) • A directed graph in which the vertices are partitioned into k≥2 disjoint sets Vi,

1≤i≤k • If <u,v> є E, then u є Vi and v є Vi+1 for some I, 1≤i<k • |V1|= |Vk|=1, and s(source) є V1 and t(sink) є Vk • c(i,j)=cost of edge <i,j>

Find a minimum­cost path from s to t

Figure 9.1 (5­stage graph)

The vertex s in V1 is called the source; the vertex t in VK is called the sink. G is usually assumed to be a weighted graph. The cost of a path from node v to node w is sum of the costs of edges in the path. The "multistage graph problem" is to find the minimum cost path from s to t. Each set Vi is called a stage in the graph.

• Many problems can be formulated as multistage graph problem – An example: resource allocation problem

• n units of resource are to be allocated to r projects • N(i,j) = net profit when j units of resource allocated to project i • V(i,j) = vertex representing the state in which a total of j units have

already been allocated to projects 1,2,..,i­1

Program to find shortest path for multistage graph using

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 90: Computer Graphics and Algorithms Lab Manual

• DP formulation Ø Every s to t path is the result of a sequence of k­2 decisions Ø The principle of optimality holds (Why?) Ø p(i,j) = a minimum­cost path from vertex j in Vi to vertex t Ø cost(i,j) = cost of path p(i,j)

• cost(k­1,j) = c(j,t) if <j,t> E, ∞ otherwise • Then computing cost(k­2,j) for all j Vk­2 • Then computing cost(k­3,j) for all j Vk­3 • … • Finally computing cost(1,s)

To find the shortest path of multi­stage graph shown in figure 9.1. – Stage 5

• cost(5,12) = 0.0 – Stage 4

• cost(4,9) = min 4+cost(5,12) = 4 • cost(4,10) = min 2+cost(5,12) = 2 • cost(4,11) = min 5+cost(5,12) = 5

– Stage 3 • cost(3,6) = min 6+cost(4,9), 5+cost(4,10) = 7 • cost(3,7) = min 4+cost(4,9), 3+cost(4,10) = 5 • cost(3,8) = min 5+cost(4,10), 6+cost(4,11) = 7

– Stage 2 • cost(2,2) = min 4+cost(3,6), 2+cost(3,7), 1+cost(3,8) = 7 • cost(2,3) = min 2+cost(3,6), 7+cost(3,7) = 9 • cost(2,4) = min 11+cost(3,8) = 18 • cost(2,5) = min 11+cost(3,7), 8+cost(3,8) = 15

– Stage 1 • cost(1,1) = min 9+cost(2,2), 7+cost(2,3), 3+cost(2,4),

2+cost(2,5) = 16

• Recording the path – d(i,j) = value of l (l is a vertex) that minimizes c(j,l)+cost(i+1,l) in

equation (5.5) – In Figure 9.1

• d(3,6)=10; d(3,7)=10; d(3,8)=10 • d(2,2)=7; d(2,3)=6; d(2,4)=8; d(2,5)=8

) , 1 ( cos ) , ( min ) , ( cos ,

1

l i t l j c j i t E l j

V l i

+ + = ∈ > <

∈ +

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 91: Computer Graphics and Algorithms Lab Manual

• d(1,1)=2 – When letting the minimum­cost path 1,v2,v3,…,vk­1,t,

• v2 = d(1,1) = 2 • v3 = d(2,d(1,1)) = 7 • v4 = d(3,d(2,d(1,1))) = d(3,7) = 10 • So the solution (minimum­cost path) is 1 2 7 10 12

and its cost is 16

Algorithm / Program Snippets:

Void multistage(graph G, int k, int n, int p[] ) // The input is a k­stage graph G = (V,E) with n vertices indexed in order // of stages. E is a set of edges and c[i][j] is the cost of <i, j>. // p[1 : k] is a minimum­cost path.

float cost[MAXSIZE]; int d[MAXSIZE], r; cost[n] = 0.0; for (int j=n­1; j >= 1; j­­) // Compute cost[j].

let r be a vertex such that <j, r> is an edge of G and c[j][r] + cost[r] is minimum; cost[j] = c[j][r] + cost[r]; d[j] = r;

// Find a minimum­cost path. p[1] = 1; p[k] =n ; for ( j=2; j <= k­1; j++) p[j] = d[ p[ j­1 ] ];

Conclusion:

• Time complexity

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 92: Computer Graphics and Algorithms Lab Manual

method.

Aim: Write a program to implement 8­queens problem using backtrack method.

Theory: Backtracking is kind of solving a problem by trial and error. However, it is a well organized trial and error. We make sure that we never try the same thing twice. We also make sure that if the problem is finite we will eventually try all possibilities (assuming there is enough computing power to try all possibilities).

General method • Useful technique for optimizing search under some constraints • Express the desired solution as an n­tuple (x1, . . . , xn) where each xi 2 Si, Si

being a finite set • The solution is based on finding one or more vectors that maximize, minimize, or

satisfy a criterion function P(x1, . . . , xn) • Sorting an array a[n]

– Find an n­tuple where the element xi is the index of ith smallest element in a – Criterion function is given by a[xi] _ a[xi+1] for 1 _ i < n – Set Si is a finite set of integers in the range [1,n]

Brute force approach – Let the size of set Si be mi – There are m = m1m2 ∙ ∙ ∙mn n­tuples that satisfy the criterion function P – In brute force algorithm, you have to form all the m n­tuples to determine the optimal solutions

Backtrack approach – Requires less than m trials to determine the solution – Form a solution (partial vector) and check at every step if this has any chance of success – If the solution at any point seems not­promising, ignore it – If the partial vector (x1, x2, . . . , xi) does not yield an optimal solution, ignore mi+1 ∙ ∙ ∙mn possible test vectors even without looking at them

• All the solutions require a set of constraints divided into two categories: explicit and implicit constraints Definition 1 Explicit constraints are rules that restrict each xi to take on values only from a given set.

– Explicit constraints depend on the particular instance I of problem being solved – All tuples that satisfy the explicit constraints define a possible solution space for I – Examples of explicit constraints

* xi >= 0, or all nonnegative real numbers * xi = 0, 1 * li<= xi <= ui

Definition 2 Implicit constraints are rules that determine which of the tuples in the solution space of I satisfy the criterion function.

Program to implement 8­queens problem using backtrack

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 93: Computer Graphics and Algorithms Lab Manual

– Implicit constraints describe the way in which the xis must relate to each other. • Determine problem solution by systematically searching the solution space for the given problem instance

– Use a tree organization for solution space • 8­queens problem

Place eight queens on an 8 × 8 chessboard so that no queen attacks another queen * Identify data structures to solve the problem * First pass: Define the chessboard to be an 8 × 8 array * Second pass: Since each queen is in a different row, define the chessboard solution to be an 8­tuple (x1, . . . , x8), where xi is the column for ith queen

– Identify explicit constraints * Explicit constraints using 8­tuple formulation are Si = 1, 2, 3, 4, 5, 6, 7,

8, 1 <= i <= 8 Solution space of 8 8 8­tuples

– Identify implicit constraints * No two xi can be the same, or all the queens must be in different columns

∙ All solutions are permutations of the 8­tuple (1, 2, 3, 4, 5, 6, 7, 8) ∙ Reduces the size of solution space from 8 8 to 8! tuples

• No two queens can be on the same diagonal • The solution above is expressed as an 8­tuple as 4, 6, 8, 2, 7, 1, 3, 5

1 2 3 4 5 6 7 8 1 Q 2 Q 3 Q 4 Q 5 Q 6 Q 7 Q 8 Q

Figure 10.1 (One Solution to 8­queen’s problem)

The 8 Queens Problem: Given is a chess board. A chess board has 8x8 fields. Is it possible to place 8 queens on this board, so that no two queens can attack each other? The n Queens problem: Given is a board of n by n squares. Is it possible to place n queens (that behave exactly like chess queens) on this board, without having any one of them attack any other queen?

1. Another example of a problem that can be solved with backtracking: o Place 8 queens on a 8x8 chess board so that no queen attack each other

(find all solutions)

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 94: Computer Graphics and Algorithms Lab Manual

52

Examples Solutions:

Figure 10.2 (Solutions to 8­queen’s problem)

Algorithm: The Backtracking Algorithm for n­Queens Problem: Position n queens on a chessboard so that no two are in the same row, column, or diagonal. Inputs: positive integer n. Outputs: all possible ways n queens can be placed on an n x n chessboard so that no two queens threaten each other. Each output consists of an array of integers col indexed from 1 to n, where col[i] is the column where the queen in the ith row is placed.

Program Snippets:

include <stdio.h> define TRUE 1 define FALSE 0

int *board;

int main()

board=(int*)calloc(8+1,sizeof(int)); board++; //here goes the userinput no of queens doesn´t matter in this code int col; int queens=2;//example from userinput for(col=1;col<=8;col++)

placeQueens(1,col,queens); void placeQueens(int row,int col,int queens)

int i; for(i=1;i<row;i++)

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

Page 95: Computer Graphics and Algorithms Lab Manual

if((board[i] == col) || ((row+col)==(i+board[i]))||((row­col)==(i­board[i]))) check= FALSE;

else check=TRUE;

if(check==TRUE) board[row]=col; if(row==8) for(i=1;i<=queens;i++) printf("(%d,%d)",i,board[i]); printf("\n");

else for(i=1;i<=8;i++) placeQueens(row+1,i);

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net