Showing posts with label c. Show all posts
Showing posts with label c. Show all posts

Volumes & Areas

/PROGRAM TO CALCULATE AREA,VOLUME,PERIMETER OF A PARTICULAR
 GEOMETRIC SHAPE/

#include
#include
#include
#define PI 3.14159
char ch;
main()
 {

clrscr();

  textcolor(4);
  intro();
  getch();
  textcolor(7);
  clrscr();
  do
   {
      ch=menu();
switch(ch)
{
  case 'a':
  case 'A':
      clrscr();
      square();
      getch();
      break;
  case 'b':
  case 'B':
      clrscr();
      rect();
      getch();
      break;
  case 'c':
  case 'C':
      clrscr();
      circl();
      getch();
      break;
  case 'd':
  case 'D':
      clrscr();
      tri();
      getch();
      break;
  case 'e':
  case 'E':
      clrscr();
      rom();
      getch();
      break;
  case 'f':
  case 'F':
      clrscr();
      para();
      getch();
      break;

  case 'g':
  case 'G':
      clrscr();
      tra();
      getch();
      break;
  case 'h':
  case 'H':
      clrscr();
      qua();
      getch();
      break;
  case 'i':
  case 'I':
      clrscr();
      semicir();
      getch();
      break;
  case 'j':
  case 'J':
      clrscr();
      msector();
      getch();
      break;

  case 'k':
  case 'K':
                      clrscr();
     sphere();
     getch();
     break;
  case 'l':
  case 'L':
      clrscr();
      cone();
      getch();
      break;
  case 'm':
  case 'M':
      clrscr();
      cyll();
      getch();
      break;

  case 'n':
  case 'N':
      clrscr();
      cube();
      getch();
      break;
  case 'o':
  case 'O':
      clrscr();
      cuboid();
      getch();
      break;
  case 'p':
  case 'P':
      clrscr();
      hemisphe();
      getch();
      break;

  case 'q':
  case 'Q':
      exit(1);
}
   } while(ch!='Q'||ch!='q');
      getch();
 }
  intro()
   {
     int i;
     clrscr();
     printf("



");
     textcolor(2);


cprintf("#################################################################
###############");
     textcolor(4);
     printf("



  PROGRAM TO CALCULATE AREAS , VOLUMES ,
CIRCUMFERENCES ");
     printf("
 
=====================================================
");
     printf("
   OF VARIOUS GEOMETRIC SHAPES");
     printf("
   ===========================

");
     textcolor(2);

cprintf("#################################################################
###############");
     getch();

     printf("





 Program developed and designed
by...

");
     printf("WWW");

   }
  menu()
   {
      clrscr();
      textcolor(7);
      printf(" MENU
Two Dimensional Shapes.
 
-----------------------
 
A.SQUARE
B.RECTANGLE
 
C.CIRCLE
D.TRIANGLE
 
E.RHOMBUS
F.PARALLELOGRAM
 
G.TRAPEZIUM
H.QUADRILATERAL.
 
I.SEMICERCLE
J.SECTOR
");
      printf("
Three Dimensional Shapes.
     
-------------------------
     
K.SPHERE
L.CONE
M.CYLLINDER
     
N.CUBE
O.CUBOID
P.HEMISPHERE
     
Q.QUIT
Enter Your Choice :");
      scanf("%c",&ch);
     return(ch);
   }

  /*****   SUB FUNCTIONS  *****/
  /*****    2 D SHAPES    *****/

   square()
    {
      float s,a,p;int i,j;
      printf("
 Enter side of square:");
      scanf("%f",&s);
      a=s*s;
      p=4*s;
      printf("
Perimeter of square  : %.3f units",p);
      printf("
Area of square       : %.3f sq.units",a);
      printf("
 Square is ...
");
      for(i=1;i<=s;i++)
{
  textcolor(10);
  for(j=1;j<=s;j++)
   cprintf("ÛÛ");
   printf("
");
 }
      return(0);
    }
   rect()
    {
     float a,p,l,b;   int i,j;
      printf("
 Enter length and breadth of rectangle:
Length:");
      scanf("%f",&l);
      printf("
Breadth:");
      scanf("%f",&b);
      a=l*b;
      p=2*(l+b);
      printf("
Perimeter of rectangle  : %.3f units",p);
      printf("
Area of rectangle       : %.3f sq.units",a);
      printf("
 Rectangle is...
");
      for(i=1;i<=b;i++)
{
  textcolor(4);
  for(j=1;j<=l;j++)
   cprintf("ÛÛ");
   printf("
");
 }
      return(0);
    }
  tri()
   {
    float area,p;
    float a,b,c,s;
    printf("
Enter three sides of triangle:");
    scanf( "%f%f%f",&a,&b,&c);
    p=a+b+c;
    s=p/2;
    area=sqrt(s*(s-a)*(s-b)*(s-c));
    printf("
Perimeter of triangle : %.3f units",p);
    printf("
Area of a triangle    : %.3f sq.units",area);
   }
  rom()
   {
     float s,d1,d2,a,p;
     printf("
Enter side and diagonals of a rhombus:
Side:");
     scanf("%f",&s);
     printf("
Diagonal :");scanf("%f",&d1);
     printf("
Diagonal :");scanf("%f",&d2);
     a=0.5*d1*d2;
     p=4*s;
     printf("
Perimeter of rhombus   :%.3f units",p);
     printf("
Area of rhombus        :%.3f sq.units",a);
   }
  circl()
   {
    float r,a,p;
    printf("Enter radius of circle:");
    scanf("%f",&r);
    a=PI * r * r;
    p=2 * PI * r;
    printf("
Circumference of circle : %.3f units",p);
    printf("
Area of circle          : %.3f sq.units",a);
   }
  para()
   {
    float a,p,base,h,l,b;
    printf("Enter height,length,breadth of parallalogram :
" );
    printf("
Height :"); scanf("%f",&h);
    printf("
Base or Length :"); scanf("%f",&l);
    printf("
Breadth :"); scanf("%f",&b);
    base=l;
    a=base*h;
    p=2 * ( l + b );
    printf("
Perimeter of parallalogram :%.3f units",p);
    printf("
Area of parallogram        :%.3f sq.units",a);

   }


  tra()
   {
    float a,b,d,are;
    printf("Enter height and lengths of two parallel sides:
Height :");
    scanf("%f",&d);
    printf("Side:"); scanf("%f",&a);
    printf("Side:"); scanf("%f",&b);
    are=0.5 * d * (a+b);
    printf("
Area of trapezium : %.3f sq.units",are);
   }
 qua()
  {
   float a,b,area,d;
   printf("Enter diagonal and perpendicular distances from opposite
vertices:
");
   printf("Diagonal :"); scanf("%f",&d);
   printf("
Distance :"); scanf("%f",&a);
   printf("
Distance :");scanf("%f",&b);
   area= 0.5 * d * (a + b);
   printf("
Area of quadrilateral : %.3f sq.units", area);
  }
 semicir()
  {
    float a,p,r;
    printf("Enter radius of semicircle:");
    scanf("%f",&r);
    a=0.5* PI * r * r;
    p= (PI * r ) + (2 * r);
    printf("
Circumference of semicircle : %.3f units",p);
    printf("
Area of semicircle          : %.3f sq.units",a);
  }

 msector()
  {
    float x,r,temp,a,p;
    printf("Enter radius and angle of sector:");
    printf("
Radius :");
    scanf("%f",&r);
    printf("
Angle(in degrees) :");
    scanf("%f",&x);
    temp= x/360;
    a= temp * (PI * r * r);
    p= temp * (2 * PI * r);
    printf("
Circumference of sector : %.3f units",p);
    printf("
Area of sector          : %.3f sq.units",a);
  }

       /******** 3 DIMENSIONAL SHAPES  *********/

  sphere()
   {
     float lsa,tsa,v,r;
     printf("Enter radius of sphere :");
     scanf("%f",&r);
     tsa=4*PI*r*r;
     v=(4.0/3.0)*PI*r*r*r;
     printf("
Total surface area of sphere   :%.3f sq.units",tsa);
     printf("
Volume of sphere               :%.3f cu.units",v);
   }
  cone()
   {
    float h,r,s ,v,tsa,lsa;
    printf("Enter base radius ,height, slant height of cone :");
    printf("
Radius :"); scanf("%f",&r);
    printf("
Height :"); scanf("%f",&h);
    printf("
Slant height :"); scanf("%f",&s);
    tsa=PI * r *(s+r);
    lsa=PI * r * s;
    v=(PI * r * r * h)/3;
    printf("
Total surface area of cone    :%.3f sq.units",tsa);
    printf("
Lateral surface area of cone  :%.3f sq.units",lsa);
    printf("
Volume of cone                :%.3f cu.units",v);
   }
  cyll()
   {
      float lsa,tsa,v,r,h;
      printf("Enter height and radius of cyllinder");
      printf("Height :"); scanf("%f",&h);
      printf("Radius :"); scanf("%f",&r);
      lsa=2*PI*r*h;
      tsa=2*PI*r*(h+r);
      v=PI*r*r*h;
      printf("
Total surface area of cyllinder  :%.3f sq.units",tsa);
      printf("
Curved surface area of cyllinder :%.3f sq.units",lsa);
      printf("
Volume of cyllinder              :%.3f cu.units",v);
   }
  cube()
   {
     float  lsa,tsa,v,s,d;
     printf("Enter side of cube :");
     scanf("%f",&s);
     d=s*sqrt(3);
     lsa=4 * s * s;
     tsa=6 * s * s;
     v= s * s * s;
     printf("
Diagonal of cube              :%.3f units",d);
     printf("
Total surface area of cube    :%.3f sq.units",tsa);
     printf("
Lateral surface area of cube  :%.3f sq.units",lsa);
     printf("
Volume of cube                :%.3f cu.units",v);
   }
  cuboid()
   {
    float lsa,tsa,v,l,b,d,h;
    printf("Enter length,breadth,height of cuboid :");
    printf("
Length :");  scanf("%f",&l);
    printf("
Breadth :");  scanf("%f",&b);
    printf("
Height :");  scanf("%f",&h);
    d=sqrt(l*l + b*b + h*h );
    lsa =2 * h *( l+b );
    tsa = lsa + 2 * l * b;
    v=l*b*h;
    printf("
Diagonal of cuboid              :%.3f units",d);
    printf("
Total surface area of cuboid    :%.3f sq.units",tsa);
    printf("
Lateral surface area of cuboid  :%.3f sq.units",lsa);
    printf("
Volume of cuboid                :%.3f cu.units",v);
   }
  hemisphe()
   {
             float lsa,tsa,v,r;
     printf("Enter radius of hemisphere :");
     scanf("%f",&r);
     tsa=3*PI*r*r;
     lsa=2*PI*r*r;
     v=(2.0/3.0)*PI*r*r*r;
     printf("
Total surface area of hemisphere    :%.3f sq.units",tsa);
     printf("
Lateral surface area of hemisphere  :%.3f sq.units",lsa);
     printf("
Volume of hemisphere                :%.3f cu.units",v);
   }

Factorial series-e^x

#include
#include
#include
long int factorial(int n);
void main()
{
 int x,i;
 float s,r;
 char c;
 clrscr();
printf("You have this series:-1+x/1! + x^2/2! + x^3/3! + x^4/4!
..x^x/x!");
 printf("
To which term you want its sum?  ");
 scanf("%d",&x);
 s=0;
 for (i=1;i<=x;i++)
  {   s=s+((float)pow(x,i)/(float)factorial(i)); }
 printf("The sum of %d terms is %f",x,1+s);
 fflush(stdin);
      getch();
}

long int factorial(int n)
 {
  if (n<=1)
return(1);
  else
n=n*factorial(n-1);
return(n);
 }

Square Root of a number by using simple calculations

#include
#include
main()
 {
  float a,b,e=0.00001,p,k;
  clrscr();
    textcolor(GREEN);
 do {
     printf("     ÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛ
");
     printf("     xDB     PROGRAM TO FIND SQUARE ROOT OF A NUMBERxDB
");
     printf("     ÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛÛ
");
    cprintf("
ENTER A NUMBER(-1 to Quit) :");
    scanf("%f",&k);

  a=k;p=a*a;
  while(p-k>=e)
   {
    b=(a+(k/a))/2;
    a=b;
    p=a*a;
   }
  printf("SQUARE ROOT IS =  %f
",a);
  getch();
  clrscr();
 }while(k!=-1);
  getch();
 }

Program to find your Day of Birth given Date of Birth

#include
#include
#include

main()
{
 clrscr();
 int d,m,y,year,month,day,i,n;
 printf("Enter how many times you want to run this program : ");
 scanf("%d",&n);
 for(i=1;i<=n;i++)
 {
 printf("

Enter the date : ");
 scanf("%d%d%d",&d,&m,&y);
 if( d>31 || m>12 || (y<1900 || y>=2000) )
  {
   printf("

INVALID INPUT
");
   getch();
   exit(0);
  }
 year = y-1900;
 year = year/4;
 year = year+y-1900;
 switch(m)
  {
   case 1:
   case 10:
   month = 1;
   break;
   case 2:
   case 3:
   case 11:
   month = 4;
   break;
   case 7:
   case 4:
  month = 0;
  break;
   case 5:
  month = 2;
  break;
   case 6:
  month = 5;
  break;
   case 8:
  month = 3;
  break;
   case 9:
   case 12:
  month = 6;
  break;
  }
 year = year+month;
 year = year+d;
 day  = year%7;
 switch(day)
  {
   case 0:
  printf("

Day is SATURDAY
");
  break;
   case 1:
  printf("

Day is SUNDAY
");
  break;
   case 2:
  printf("

Day is MONDAY
");
  break;
   case 3:
  printf("

Day is TUESDAY
");
  break;
   case 4:
  printf("

Day is WEDNESDAY
");
  break;
   case 5:
  printf("

Day is THURSDAY
");
  break;
   case 6:
  printf("

Day is FRIDAY
");
  break;
  }
}
 getch();
 return 0;
}

Program to calculate Area of a Polygon

/* Given the coordinates of the vertices of a convex polygon,
   calculate its area and perimeter. Subdivide it into triangles
   and calculate the area of each triangle with Heron's formula.
   Requires data file pvert.txt containing coordinates of each vertex.
   Example of data for a polygon with 5 vertices:

   3 7 6 4 3 -2 -6 1 -6 7
*/
#include
#include
#include
#define MAX_VERT 50
enum {x, y};
typedef struct triangle {
    double v1[2];
    double v2[2];
    double v3[2];
} triangle;
double area(triangle a);
double perimeter(double *vertices, int size);
double side(double *p1, double *p2);

int main(void)
{
  int n, idx;
  int triangles;
  int index;
  int xycount;
  double xy;
  double triangle_area;
  double polygon_area;
  double perim;
  double polygon_vertices[MAX_VERT] = {0.0};
  triangle a;
  FILE *data;

  xycount = 0;
  polygon_area = 0;
  if((data = fopen("pvert.txt", "r")) == NULL)
  {
    fprintf(stderr, "can't open data file
");
    exit(EXIT_FAILURE);
  }

  /* Read x-y coordinates of the vertices
     of the polygon from a file. */
  while(fscanf(data, "%lf", &xy) == 1)
    polygon_vertices[xycount++] = xy;
  fclose(data);
  idx = 0;
  /* triangles in polygon = vertices - 2 */
  triangles = (xycount / 2) - 2;
  putchar('
');

  for(index = 2, idx = 0; idx < triangles; index += 2, ++idx)
  {
  /* Load vertices of a triangle into struct.
     1st vertex of the polygon will be the 1st
     vertex of each triangle. index holds the
     starting index of each consecutive set of
     triangle vertices after the 1st. */
    a.v1[x] = polygon_vertices[0];
    a.v1[y] = polygon_vertices[1];
    a.v2[x] = polygon_vertices[index+0];
    a.v2[y] = polygon_vertices[index+1];
    a.v3[x] = polygon_vertices[index+2];
    a.v3[y] = polygon_vertices[index+3];

    /* calculate the area of the triangle */
    triangle_area = area(a);
    printf("area of triangle = %.2f
", triangle_area);

    /* add triangle area to polygon area */
    polygon_area += triangle_area;
  }
  printf("
area of polygon = %.2f
", polygon_area);

  /* calculate the perimeter of the polygon */
  perim = perimeter(polygon_vertices, xycount);
  printf("perimeter of polygon = %.2f
", perim);

  return 0;
}

/* calculate triangle area with Heron's formula */
double area(triangle a)
{
  double s1, s2, s3, S, area;

  s1 = side(a.v1, a.v2);
  s2 = side(a.v2, a.v3);
  s3 = side(a.v3, a.v1);
  S = (s1 + s2 + s3) / 2;
  area = sqrt(S*(S - s1)*(S - s2)*(S - s3));

  return area;
}

/* calculate polygon perimeter */
double perimeter(double *vertices, int size)
{
  int idx, jdx;
  double p1[2], p2[2], pfirst[2], plast[2];
  double perimeter;

  perimeter = 0.0;
  /* 1st vertex of the polygon */
  pfirst[x] = vertices[0];
  pfirst[y] = vertices[1];
  /* last vertex of polygon */
  plast[x] = vertices[size-2];
  plast[y] = vertices[size-1];
  /* calculate perimeter minus last side */
  for(idx = 0; idx <= size-3; idx += 2)
  {
    for(jdx = 0; jdx < 4; ++jdx)
    {
      p1[x] = vertices[idx];
      p1[y] = vertices[idx+1];
      p2[x] = vertices[idx+2];
      p2[y] = vertices[idx+3];
    }
    perimeter += side(p1, p2);
  }
  /* add last side */
  perimeter += side(plast, pfirst);

  return perimeter;
}

/* calculate length of side */
double side(double *p1, double *p2)
{
  double s1, s2, s3;

  s1 = (p1[x] - p2[x]);
  s2 = (p1[y] - p2[y]);
  s3 = (s1 * s1) + (s2 * s2);

  return sqrt(s3);
}

Program for Decimal to Roman Number conversion

#include

main()
{
int a,b,c,d,e;
clrscr();
printf("Input a  number (between 1-3000):");
scanf("%d",&e);
while (e==0||e>3000)
       {
       printf ("ERROR: Invalid Input!
");
       printf ("Enter the number again:");
       scanf ("%d",&e);
       }
if (e>3000)
printf("Invalid");
a = (e/1000)*1000;
b = ((e/100)%10)*100;
c = ((e/10)%10)*10;
d = ((e/1)%10)*1;

if (a ==1000)
printf("M");
else if (a ==2000)
printf("MM");
else if (a ==3000)
printf("MMM");

if (b == 100)
printf("C");
else if (b == 200)
printf("CC");
else if (b == 300)
printf("CCC");
else if (b == 400)
printf("CD");
else if (b ==500)
printf("D");
else if (b == 600)
printf("DC");
else if (b == 700)
printf("DCC");
else if (b ==800)
printf("DCCC");
else if (b == 900)
printf("CM");


if (c == 10)
printf("X");
else if (c == 20)
printf("XX");
else if (c == 30)
printf("XXX");
else if (c == 40)
printf("XL");
else if (c ==50)
printf("L");
else if (c == 60)
printf("LX");
else if (c == 70)
printf("LXX");
else if (c ==80)
printf("LXXX");
else if (c == 90)
printf("XC");

if (d == 1)
printf("I");
else if (d == 2)
printf("II");
else if (d == 3)
printf("III");
else if (d == 4)
printf("IV");
else if (d ==5)
printf("V");
else if (d == 6)
printf("VI");
else if (d == 7)
printf("VII");
else if (d ==8)
printf("VIII");
else if (d == 9)
printf("IX");
getch();
}

Progam that gives all details of a Triangle given the lengths of its sides

#include
#include
#include
#include

main()
{
 clrscr();
 float a,b,c,S,D,A,B,C,Area,R;
 printf("Enter the lengths of the three sides of the triangle :

");
 scanf("%f%f%f",&a,&b,&c);

 S = (a+b+c)/2.0;        // S is the semiperimeter of the triangle
 D = S*(S-a)*(S-b)*(S-c);//D is the square of the area of the triangle
 if(D<=0)
 {
  printf("
The triangle cannot be formed");
  getch();
  exit(0);
 }

 if((a==b || b==c || c==a) && !(a==b && b==c && c==a))
// this complex logic is to eliminate interpretting a triangle with all
three
// sides equal as both isosceles and equilateral.
   printf("
The triangle is ISOSCELES

");
 if(a==b && b==c && c==a)
   printf("
The triangle is EQUILATERAL

");
 if(a!=b && b!=c && c!=a)
  printf("
The triangle is SCALENE

");

 Area = sqrt(D);
 R = (a*b*c)/(4.0*Area);
 printf("PERIMETER     = %.2f units
",(2.0*S));
 printf("AREA          = %.2f sq.units
",Area);
 printf("CIRCUM RADIUS = %.2f units
",R);
// using sine rule,we get...
 A = (180.0/3.1415926)*asin(a/(2.0*R));//  value of pi should be upto 7
 B = (180.0/3.1415926)*asin(b/(2.0*R));//  decimal places of accuracy and
also
 C = (180.0/3.1415926)*asin(c/(2.0*R));//  note that the 7th decimal place
is
       //  6 and not 7 as it had to be if were
 if(A==90.0 || B==90.0 || C==90.0)     //  approximated to 7 decimal
places
  printf("
The triangle is RIGHT ANGLED
");
 if(A<90.0 && B<90.0 && C<90.0)
  printf("
The triangle is ACUTE ANGLED
");
 if(A>90.0 || B>90.0 || C>90.0)
  printf("
The triangle is OBTUSE ANGLED
");

 printf("
The angles are as follows :

");
 printf("A = %.2f degrees
",A);
 printf("B = %.2f degrees
",B);
 printf("C = %.2f degrees
",C);
 printf("
Where A,B,C stand for angles opposite to sides
%.2f,%.2f,%.2f",a,b,c);
 printf(" respectively
");


 getch();
 return 0;
}

Circle Through Three Points

#include
#include
#include

int main()
{
clrscr();
double f,g,m,x1,x2,x3,y1,y2,y3;
double c,d,h,e,k,r,s;
for(;;)
{
if(scanf("%lf %lf %lf %lf %lf %lf",&x1,&y1,&x2,&y2,&x3,&y3)==EOF)
//checking for input
break;

f = x3*x3-x3*x2-x1*x3+x1*x2+y3*y3-y3*y2-y1*y3+y1*y2; //formula
g = x3*y1-x3*y2+x1*y2-x1*y3+x2*y3-x2*y1;

if(g==0)
  m = 0;
else
  m = (f/g);

c = (m*y2)-x2-x1-(m*y1); //formula
d = (m*x1)-y1-y2-(x2*m);
e = (x1*x2)+(y1*y2)-(m*x1*y2)+(m*x2*y1);

h = (c/2); //formula
k = (d/2);
s = (((h)*(h))+((k)*(k))-e);
r = pow(s,.5);

printf("(x");

if(h>=0)
  printf(" + ");
else if(h<0)
  printf(" - ");
if(h<0)
  h=-h;
printf("%.3lf)^2",(h));
printf(" + ");
printf("(y");
if(k>=0)
  printf(" + ");
else if(k<0)
  printf(" - ");
if(k<0)
  k=-k;
printf("%.3lf)^2 = %.3lf^2",(k),r);

printf("
");

printf("x^2 + y^2");

if(c>=0) printf(" + ");
else if(c<0) printf(" - ");

if(c<0) c=-c;
printf("%.3lfx",c);

if(d>=0) printf(" + ");
else if(d<0) printf(" - ");

if(d<0) d=-d;
printf("%.3lfy",d);

if(e>=0) printf(" + ");
else if(e<0) printf(" - ");

if(e<0) e=-e;
printf("%.3lf = 0",e);
printf("

");
}

getch();
return 0;
}

Treesort [string array]

#include

#include

#include


struct tnode { 

 char *str;

 struct tnode *left; 

 struct tnode *right; 

};


void insert(struct tnode **p, char *value);

void print(struct tnode *root);


int main(void) {

 char line[1024];

 struct tnode *root;


 root = NULL;

 while((fgets(line, 1024, stdin)) != NULL)

  insert(&root, line);


 print(root);

 return 0;

}


/* call by reference .. ! */

void insert(struct tnode **p, char *value) {

 if(!*p) {

  *p = (struct tnode *)malloc(sizeof(struct tnode));

  (*p)->left = (*p)->right = NULL;

  (*p)->str = strdup(value);

  return;

 }


 if(strcmp(value, (*p)->str) < 0)

  insert(&(*p)->left, value);

 else 

  insert(&(*p)->right, value);

}

 

/* inorder binary tree print ... */

void print(struct tnode *root) {

 if(root != NULL) {

  print(root->left);

  printf("%s", root->str); 

  print(root->right);

 }

}


Ssort, selection sort [array]

#include

void selection_sort(int a[], int size);

int main(void) {
 int arr[10] = {10, 2, 4, 1, 6, 5, 8, 7, 3, 9};
 int i = 0;

 printf("before:\n");
 for(i = 0; i < 10; i++) printf("%d ", arr[i]);
 printf("\n");

 selection_sort(arr, 10);

 printf("after:\n");
 for(i = 0; i < 10; i++) printf("%d ", arr[i]);
 printf("\n");

 return 0;
}

void selection_sort(int a[], int size) {
 int i = 0;
 int j = 0;
 int large = 0;
 int index = 0;

 for(i = size - 1; i > 0; i--) {
  large = a[0];
  index = 0;
  for(j = 1; j <= i; j++)
   if(a[j] > large) {
    large = a[j];
    index = j;
   }
   a[index] = a[i];
   a[i] = large;
 }
}

Shsort, shell sort [array]

#include

#define MAXARRAY 10

void shellsort(int a[], int total, int index);

int main(void) {
 int array[MAXARRAY] = {0};
 int i = 0;

 /* load some random values into the array */
 for(i = 0; i < MAXARRAY; i++)
  array[i] = rand() % 100;

 /* print the original array */
 printf("Before shellsort: ");
 for(i = 0; i < MAXARRAY; i++) {
  printf(" %d ", array[i]);
 }
 printf("\n");

 shellsort(array, MAXARRAY, 1);

 /* print the `shellsorted' array */
 printf("After  shellsort: ");
 for(i = 0; i < MAXARRAY; i++) {
  printf(" %d ", array[i]);
 }
 printf("\n");

 return 0;
}

void shellsort(int a[], int total, int index) {
 int i = 0;
 int j = 0;
 int k = 0;
 int l = 0;

 for(k = 0; k < index; k++) {
  for(i = k; i < total; i += index) {
   l = a[i];
   for(j = (i - index); j >= 0; j -= index) {
    if(a[j] > l)
     a[j + index] = a[j];
    else
     break;
   }
   a[j + index] = l;
  }
 }

 return;
}

Selection sort [linked list]

#include
#include

#define MAX 10

struct lnode {
 int data;
 struct lnode *next;
} *head, *visit;

/* add a new entry to the linked list */
void llist_add(struct lnode **q, int num);
/* preform a selection sort on the linked list */
void llist_selection_sort(void);
/* print the entire linked list */
void llist_print(void);

int main(void) {
 /* linked list */
 struct lnode *newnode = NULL;
 int i = 0; /* a general counter */

 /* load some random values into the linked list */
 for(i = 0; i < MAX; i++) {
  llist_add(&newnode, (rand() % 100));
 }

 head = newnode;
 printf("Before selection sort:\n");
 llist_print();
 printf("After  selection sort:\n");
 llist_selection_sort();
 llist_print();

 return 0;
}

/* adds a node at the end of a linked list */
void llist_add(struct lnode **q, int num) {
 struct lnode *temp;

 temp = *q;

 /* if the list is empty, create first node */
 if(*q == NULL) {
  *q = malloc(sizeof(struct lnode));
   temp = *q;
 } else {
  /* go to last node */
  while(temp->next != NULL)
   temp = temp->next;

   /* add node at the end */
   temp->next = malloc(sizeof(struct lnode));
   temp = temp->next;
 }

 /* assign data to the last node */
 temp->data = num;
 temp->next = NULL;
}

/* print the entire linked list */
void llist_print(void) {
 visit = head;

 /* traverse the entire linked list */
 while(visit != NULL) {
  printf("%d ", visit->data);
  visit = visit->next;
 }
 printf("\n");
}

void llist_selection_sort(void) {
 struct lnode *a = NULL;
 struct lnode *b = NULL;
 struct lnode *c = NULL;
 struct lnode *d = NULL;
 struct lnode *tmp = NULL;

 a = c = head;
 while(a->next != NULL) {
  d = b = a->next;
  while(b != NULL) {
   if(a->data > b->data) {
    /* neighboring linked list node */
    if(a->next == b) {
     if(a == head) {
      a->next = b->next;
      b->next = a;
      tmp = a;
      a = b;
      b = tmp;
      head = a;
      c = a;
      d = b;
      b = b->next;
     } else {
      a->next = b->next;
      b->next = a;
      c->next = b;
      tmp = a;
      a = b;
      b = tmp;
      d = b;
      b = b->next;
     }
    } else {
     if(a == head) {
      tmp = b->next;
      b->next = a->next;
      a->next = tmp;
      d->next = a;
      tmp = a;
      a = b;
      b = tmp;
      d = b;
      b = b->next;
      head = a;
    } else {
     tmp = b->next;
     b->next = a->next;
     a->next = tmp;
     c->next = b;
     d->next = a;
     tmp = a;
     a = b;
     b = tmp;
     d = b;
     b = b->next;
    }
   }
  } else {
   d = b;
   b = b->next;
  }
 }
  c = a;
  a = a->next;
 }
}

Qsort [string, dynamic pointer array]

#include
#include
#include

void sortstrarr(void *array, unsigned n);
static int cmpr(const void *a, const void *b);

int main (void) {
 char **strarray = NULL;
 int i = 0, strcount = 0;
 char line[1024];

 while((fgets(line, 1024, stdin)) != NULL) {
  if(strlen(line) == 1)
   continue;

  strarray = (char **)realloc(strarray, (strcount + 1) * sizeof(char *));
  strarray[strcount++] = strdup(line);
 }
                
 printf("### Before ###\n");
 for(i = 0; i < strcount; i++)
  printf("%2d: %s", i, strarray[i]);

 sortstrarr(strarray, strcount);

 printf("### After ###\n");
 for(i = 0; i < strcount; i++)
  printf("%2d: %s", i, strarray[i]);

 /* free mem... */
 for(i = 0; i < strcount; i++)
  free(strarray[i]);

 free(strarray);
 return 0;
}

static int cmpr(const void *a, const void *b) {
 return strcmp(*(char **)a, *(char **)b);
}

void sortstrarr(void *array, unsigned n) {
 qsort(array, n, sizeof(char *), cmpr);
}

Qsort [string array]

#include
#include
#include

void sortstrarr(void *array, unsigned n);
static int cmpr(const void *a, const void *b);

int main(void) {
 char line[1024];
 char *line_array[1024];
 int i = 0;
 int j = 0;

 while((fgets(line, 1024, stdin)) != NULL)
  if(i < 1024)
   line_array[i++] = strdup(line);
  else
   break;

 sortstrarr(line_array, i);

 while(j < i)
  printf("%s", line_array[j++]);

 return 0;
}

static int cmpr(const void *a, const void *b) {
 return strcmp(*(char **)a, *(char **)b);
}

void sortstrarr(void *array, unsigned n) {
 qsort(array, n, sizeof(char *), cmpr);
}

Qsort [array of pointers to structures]

#include
#include
#include

struct node {
 char *str;
};

/* compare function for qsort */
static int cmpr(const void *a, const void *b);

int main(void) {
 struct node **strarray = NULL;
 int i = 0, count = 0;
 char line[1024];

 while(fgets(line, 1024, stdin) != NULL) {
  /* add ONE element to the array */
  strarray = (struct node **)realloc(strarray, (count + 1) * sizeof(struct node *));

  /* allocate memory for ONE `struct node` */
  strarray[count] = (struct node *)malloc(sizeof(struct node));

  /* copy the data into the new element (structure) */
  strarray[count]->str = strdup(line);
  count++;
 }

 /* before sorting ... */
 printf("Before:\n");
 for(i = 0; i < count; i++) {
  printf("[%d]->str: %s", i, strarray[i]->str);
 }

 /* qsort array of structures */
 qsort(strarray, count, sizeof(*strarray), cmpr);

 /* after sorting ... */
 printf("\n--\nAfter:\n");
 for(i = 0; i < count; i++) {
  printf("[%d]->str: %s", i, strarray[i]->str);
 }

 /* free all strarray elements */
 for(i = 0; i < count; i++) {
  free(strarray[i]->str);
  free(strarray[i]);
  i++;
 }
 free(strarray);
 
 return 0;
}

/* compare function for qsort */
static int cmpr(const void *a, const void *b) {
 struct node * const *one = a;
 struct node * const *two = b;

 return strcmp((*one)->str, (*two)->str);
}

Qcksort, quick sort [array]

#include

#define MAXARRAY 10

void quicksort(int arr[], int low, int high);

int main(void) {
 int array[MAXARRAY] = {0};
 int i = 0;

 /* load some random values into the array */
 for(i = 0; i < MAXARRAY; i++)
  array[i] = rand() % 100;

 /* print the original array */
 printf("Before quicksort: ");
 for(i = 0; i < MAXARRAY; i++) {
  printf(" %d ", array[i]);
 }
 printf("\n");

 quicksort(array, 0, (MAXARRAY - 1));

 /* print the `quicksorted' array */
 printf("After  quicksort: ");
 for(i = 0; i < MAXARRAY; i++) {
  printf(" %d ", array[i]);
 }
 printf("\n");

 return 0;
}

/* sort everything inbetween `low' <-> `high' */
void quicksort(int arr[], int low, int high) {
 int i = low;
 int j = high;
 int y = 0;
 /* compare value */
 int z = arr[(low + high) / 2];

 /* partition */
 do {
  /* find member above ... */
  while(arr[i] < z) i++;

  /* find element below ... */
  while(arr[j] > z) j--;

  if(i <= j) {
   /* swap two elements */
   y = arr[i];
   arr[i] = arr[j];
   arr[j] = y;
   i++;
   j--;
  }
 } while(i <= j);

 /* recurse */
 if(low < j)
  quicksort(arr, low, j);

 if(i < high)
  quicksort(arr, i, high);
}

No sort, but reversing a [linked list]

#include
#include

#define MAX 10    /* max of 10 elements */

struct lnode {
 int number;
 struct lnode *next;
};

/* add a lnode at the beginning of the list */
void llist_add_begin(struct lnode **n, int val);
/* reverse the whole list */
void llist_reverse(struct lnode **n);
/* display the whole linked list */
void llist_display(struct lnode *n);

int main(void) {
 struct lnode *new = NULL;
 int i = 0;

 /* insert some numbers */
 for(i = 0; i <= MAX; i++)
  llist_add_begin(&new, i);

 printf("linked list before reversal:");
 llist_display(new);
 llist_reverse(&new);
 printf("linked list after  reversal:");
 llist_display(new);

 return 0;
}

/* add a lnode at the beginning of the list */
void llist_add_begin(struct lnode **n, int val)  {
 struct lnode *temp = NULL;

 /* add new node */
 temp = malloc(sizeof(struct lnode));
 temp->number = val;
 temp->next = *n;
 *n = temp;
}

/* reverse the whole list */
void llist_reverse(struct lnode **n)  {
 struct lnode *a = NULL;
 struct lnode *b = NULL;
 struct lnode *c = NULL;
 a = *n, b = NULL;

 while(a != NULL) {
  c = b, b = a, a = a->next;
  b->next = c;
 }

 *n = b;
}

/* display the whole linked list */
void llist_display(struct lnode *n) {
 while(n != NULL)
  printf(" %d", n->number), n = n->next;

 printf("\n");
}

Msort, merge sort [array]

#include
#include

#define MAXARRAY 10

void mergesort(int a[], int low, int high);

int main(void) {
 int array[MAXARRAY];
 int i = 0;

 /* load some random values into the array */
 for(i = 0; i < MAXARRAY; i++)
  array[i] = rand() % 100;

 /* array before mergesort */
 printf("Before    :");
 for(i = 0; i < MAXARRAY; i++)
  printf(" %d", array[i]);

 printf("\n");

 mergesort(array, 0, MAXARRAY - 1);

 /* array after mergesort */
 printf("Mergesort :");
 for(i = 0; i < MAXARRAY; i++)
  printf(" %d", array[i]);

 printf("\n");
 return 0;
}

void mergesort(int a[], int low, int high) {
 int i = 0;
 int length = high - low + 1;
 int pivot  = 0;
 int merge1 = 0;
 int merge2 = 0;
 int working[length];

 if(low == high)
  return;

 pivot  = (low + high) / 2;

 mergesort(a, low, pivot);
 mergesort(a, pivot + 1, high);

 for(i = 0; i < length; i++)
  working[i] = a[low + i];

 merge1 = 0;
 merge2 = pivot - low + 1;

 for(i = 0; i < length; i++) {
  if(merge2 <= high - low)
   if(merge1 <= pivot - low)
    if(working[merge1] > working[merge2])
     a[i + low] = working[merge2++];
    else
     a[i + low] = working[merge1++];
   else
    a[i + low] = working[merge2++];
  else
   a[i + low] = working[merge1++];
 }
}

Merge sort [linked list]

#include
#include

struct node {
 int number;
 struct node *next;
};

/* add a node to the linked list */
struct node *addnode(int number, struct node *next);
/* preform merge sort on the linked list */
struct node *mergesort(struct node *head);
/* merge the lists.. */
struct node *merge(struct node *head_one, struct node *head_two);

int main(void) {
 struct node *head;
 struct node *current;
 struct node *next;
 int test[] = {8, 3, 2, 6, 1, 5, 4, 7, 9, 0};
 int i;

 head = NULL;
 /* insert some numbers into the linked list */
 for(i = 0; i < 10; i++)
  head = addnode(test[i], head);

 /* sort the list */
 head = mergesort(head);

 /* print the list */
 printf(" before  after\n"), i = 0;
 for(current = head; current != NULL; current = current->next)
  printf("%4d\t%4d\n", test[i++], current->number);

 /* free the list */
 for(current = head; current != NULL; current = next)
  next = current->next, free(current);

 /* done... */
 return 0;
}

/* add a node to the linked list */
struct node *addnode(int number, struct node *next) {
 struct node *tnode;

 tnode = (struct node*)malloc(sizeof(*tnode));

 if(tnode != NULL) {
  tnode->number = number;
  tnode->next = next;
 }

 return tnode;
}

/* preform merge sort on the linked list */
struct node *mergesort(struct node *head) {
 struct node *head_one;
 struct node *head_two;

 if((head == NULL) || (head->next == NULL)) 
  return head;

 head_one = head;
 head_two = head->next;
 while((head_two != NULL) && (head_two->next != NULL)) {
  head = head->next;
  head_two = head->next->next;
 }
 head_two = head->next;
 head->next = NULL;

 return merge(mergesort(head_one), mergesort(head_two));
}

/* merge the lists.. */
struct node *merge(struct node *head_one, struct node *head_two) {
 struct node *head_three;

 if(head_one == NULL) 
  return head_two;

 if(head_two == NULL) 
  return head_one;

 if(head_one->number < head_two->number) {
  head_three = head_one;
  head_three->next = merge(head_one->next, head_two);
 } else {
  head_three = head_two;
  head_three->next = merge(head_one, head_two->next);
 }

 return head_three;
}

Isort, insertion sort [array]

#include

void isort(float arr[], int n);
int fm(float arr[], int b, int n);

int main(void) {
 float arr1[5] = {4.3, 6.7, 2.8, 8.9, 1.0};
 float arr2[5] = {4.3, 6.7, 2.8, 8.9, 1.0};
 int i = 0;

 isort(arr2, 5);

 printf("\nBefore\tAfter\n--------------\n");

 for(i = 0; i < 5; i++)
  printf("%.2f\t%.2f\n", arr1[i], arr2[i]);

 return 0;
}

int fm(float arr[], int b, int n) {
 int f = b;
 int c;

 for(c = b + 1; c < n; c++)
  if(arr[c] < arr[f])
   f = c;

 return f;
}

void isort(float arr[], int n) {
 int s, w;
 float sm;

 for(s = 0; s < n - 1; s++) {
  w = fm(arr, s, n);
  sm = arr[w];
  arr[w] = arr[s];
  arr[s] = sm;
 }
}