Sunday, November 21, 2010

Draw a Sierpinski triangle

Share Orkut
#include<stdio.h>
#include<graphics.h>
#include<math.h>
#define pi 3.142857
#define ROUND(a)((int)(a+0.5))
int max;
void DDA(int xa,int ya,int xb,int yb)
{
 int dx,dy,steps,k;
 dx=xb-xa;
 dy=yb-ya;
 float x=xa,y=ya,xinc,yinc;
 if(abs(dx)>abs(dy))
  steps=abs(dx);
 else
  steps=abs(dy);
 xinc=dx/(float)steps;
 yinc=dy/(float)steps;
 putpixel(ROUND(x),ROUND(y),5);
 for(k=0;k<steps;k++)
 {
  x+=xinc;
  y+=yinc;
  putpixel(ROUND(x),ROUND(y),5);
 } 
}
float minside(int x1,int y1,int x2,int y2,int x3,int y3)
{
 float a,b,c,s;
 a=sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
 b=sqrt((x2-x3)*(x2-x3)+(y2-y3)*(y2-y3));
 c=sqrt((x1-x3)*(x1-x3)+(y1-y3)*(y1-y3));
 if(a>b)
  s=a;
 else
  s=b;
 if(s>c)
  s=c;
 return s;
}
void triangle(int x1,int y1,int x2,int y2,int x3,int y3,int i)
{ 

 float newx1,newy1,newx2,newy2,newx3,newy3;
 i++;
 if(i==max)
  return;
 else
 {
  DDA(x1,y1,x2,y2);
  DDA(x2,y2,x3,y3);
  DDA(x3,y3,x1,y1);
  newx1=(x1+x2)/2 ;
  newy1=(y1+y2)/2;
  newx2=(x2+x3)/2 ;
  newy2=(y2+y3)/2;
  newx3=(x1+x3)/2 ;
  newy3=(y1+y3)/2;
  triangle(x1,y1,newx1,newy1,newx3,newy3,i);
  triangle(x2,y2,newx1,newy1,newx2,newy2,i);
  triangle(x3,y3,newx2,newy2,newx3,newy3,i);
 }
}
int main()
{
 int gd=DETECT,gm=VGAMAX;
 int x1,y1,x2,y2,x3,y3;
 float small;
 printf("\n Enter the 1st coordinates of the triangle");
 scanf("%d%d",&x1,&y1);
 printf("\n enter the 2nd coordinates of the triangle");
 scanf("%d%d",&x2,&y2);
 printf("\n enter the 3rd coordinates of the triangle");
 scanf("%d%d",&x3,&y3);
 initgraph(&gd,&gm,"null");
 small=minside(x1,y1,x2,y2,x3,y3);
 max=2+(int)small/20;
 triangle(x1,y1,x2,y2,x3,y3,0);
 while (!kbhit());
 closegraph();
 return 0;
}

No comments:

Post a Comment