Saturday 7 November 2015

rb tree insertion


#include<stdio.h>
#include<stdlib.h>

//A Red-Black tree node structure
struct node
{
    int data;     // for data part
    char color;  // for color property

    //links for left, right children and parent
    struct node *left, *right, *parent;
};


// Left Rotation
void LeftRotate(struct node **root,struct node *x)
{
    //y stored pointer of right child of x
    struct node *y = x->right;

    //store y's left subtree's pointer as x's right child
    x->right = y->left;

    //update parent pointer of x's right
    if (x->right != NULL)
        x->right->parent = x;

    //update y's parent pointer
    y->parent = x->parent;

    // if x's parent is null make y as root of tree
    if (x->parent == NULL)
        (*root) = y;

    // store y at the place of x
    else if (x == x->parent->left)
        x->parent->left = y;
    else    x->parent->right = y;

    // make x as left child of y
    y->left = x;

    //update parent pointer of x
    x->parent = y;
}


// Right Rotation (Similar to LeftRotate)
void rightRotate(struct node **root,struct node *y)
{
    struct node *x = y->left;
    y->left = x->right;
    if (x->right != NULL)
        x->right->parent = y;
    x->parent =y->parent;
    if (x->parent == NULL)
        (*root) = x;
    else if (y == y->parent->left)
        y->parent->left = x;
    else y->parent->right = x;
    x->right = y;
    y->parent = x;
}

// Utility function to fixup the Red-Black tree after standard BST insertion
void insertFixUp(struct node **root,struct node *z)
{
    // iterate until z is not the root and z's parent color is red
    while (z != *root && z->parent->color == 'R')
    {
        struct node *y;

        // Find uncle and store uncle in y
        if (z->parent == z->parent->parent->left)
            y = z->parent->parent->right;
        else
            y = z->parent->parent->left;

        // If uncle is RED, do following
        // (i)  Change color of parent and uncle as BLACK
        // (ii) Change color of grandparent as RED
        // (iii) Move z to grandparent
        if (y->color == 'R')
        {
            y->color = 'B';
            z->parent->color = 'B';
            z->parent->parent->color = 'R';
            z = z->parent->parent;
        }

        // Uncle is BLACK, there are four cases (LL, LR, RL and RR)
        else
        {
            // Left-Left (LL) case, do following
            // (i)  Swap color of parent and grandparent
            // (ii) Right Rotate Grandparent
            if (z->parent == z->parent->parent->left &&
                z == z->parent->left)
            {
                char ch = z->parent->color ;
                z->parent->color = z->parent->parent->color;
                z->parent->parent->color = ch;
                rightRotate(root,z->parent->parent);
            }

            // Left-Right (LR) case, do following
            // (i)  Swap color of current node  and grandparent
            // (ii) Left Rotate Parent
            // (iii) Right Rotate Grand Parent
            if (z->parent == z->parent->parent->left &&
                z == z->parent->right)
            {
                char ch = z->color ;
                z->color = z->parent->parent->color;
                z->parent->parent->color = ch;
                LeftRotate(root,z->parent);
                rightRotate(root,z->parent->parent);
            }

            // Right-Right (RR) case, do following
            // (i)  Swap color of parent and grandparent
            // (ii) Left Rotate Grandparent
            if (z->parent == z->parent->parent->right &&
                z == z->parent->right)
            {
                char ch = z->parent->color ;
                z->parent->color = z->parent->parent->color;
                z->parent->parent->color = ch;
                LeftRotate(root,z->parent->parent);
            }

            // Right-Left (RL) case, do following
            // (i)  Swap color of current node  and grandparent
            // (ii) Right Rotate Parent
            // (iii) Left Rotate Grand Parent
            if (z->parent == z->parent->parent->right &&
                z == z->parent->left)
            {
                char ch = z->color ;
                z->color = z->parent->parent->color;
                z->parent->parent->color = ch;
                rightRotate(root,z->parent);
                LeftRotate(root,z->parent->parent);
            }
        }
    }
    (*root)->color = 'B'; //keep root always black
}

// Utility function to insert newly node in RedBlack tree
void insert(struct node **root, int data)
{
    // Allocate memory for new node
    struct node *z = (struct node*)malloc(sizeof(struct node));
    z->data = data;
    z->left = z->right = z->parent = NULL;

     //if root is null make z as root
    if (*root == NULL)
    {
        z->color = 'B';
        (*root) = z;
    }
    else
    {
        struct node *y = NULL;
        struct node *x = (*root);

        // Follow standard BST insert steps to first insert the node
        while (x != NULL)
        {
            y = x;
            if (z->data < x->data)
                x = x->left;
            else
                x = x->right;
        }
        z->parent = y;
        if (z->data > y->data)
            y->right = z;
        else
            y->left = z;
        z->color = 'R';

        // call insertFixUp to fix reb-black tree's property if it
        // is voilated due to insertion.
        insertFixUp(root,z);
    }
}

// A utility function to traverse Red-Black tree in inorder fashion
void inorder(struct node *root)
{
    if (root == NULL)
        return;
    inorder(root->left);
    printf("%d ", root->data);
    inorder(root->right);
}

/* Drier program to test above function*/
int main()
{
    struct node *root = NULL;
    insert(&root,5);
    insert(&root,3);
    insert(&root,7);
    insert(&root,2);
    insert(&root,4);
    insert(&root,6);
    insert(&root,8);
    insert(&root,11);
    printf("inorder Traversal Is : ");
    inorder(root);

    return 0;
}

lcs


#include<stdio.h>
#include<string.h>

int i,j,m,n,c[20][20];
char x[20],y[20],b[20][20];

void print(int i,int j)
{
                if(i==0 || j==0)
                                return;
                if(b[i][j]=='c')
                {
                                print(i-1,j-1);
                                printf("%c",x[i-1]);
                }
                else if(b[i][j]=='u')
                                print(i-1,j);
                else
                                print(i,j-1);
}

void lcs()
{
                m=strlen(x);
                n=strlen(y);
                for(i=0;i<=m;i++)
                                c[i][0]=0;
                for(i=0;i<=n;i++)
                                c[0][i]=0;
                               
                //c, u and l denotes cross, upward and downward directions respectively
                for(i=1;i<=m;i++)
                                for(j=1;j<=n;j++)
                                {
                                                if(x[i-1]==y[j-1])
                                                {
                                                                c[i][j]=c[i-1][j-1]+1;
                                                                b[i][j]='c';
                                                }
                                                else if(c[i-1][j]>=c[i][j-1])
                                                {
                                                                c[i][j]=c[i-1][j];
                                                                b[i][j]='u';
                                                }
                                                else
                                                {
                                                                c[i][j]=c[i][j-1];
                                                                b[i][j]='l';
                                                }
                                }
}

int main()
{
                printf("Enter 1st sequence:");
                scanf("%s",x);
                printf("Enter 2nd sequence:");
                scanf("%s",y);
                printf("\nThe Longest Common Subsequence is ");
                lcs();
                print(m,n);
        return 0;
}

tower of honoi


#include <stdio.h>




void
towers(
int
,
char
,
char
,
char
);




int
main()

{

 
int
num;




 
printf
(
"Enter the number of disks : "
);

 
scanf
(
"%d"
, &num);

 
printf
(
"The sequence of moves involved in the Tower of Hanoi are :\n"
);

 
towers(num,
'A'
,
'C'
,
'B'
);

 
return
0;

}

void
towers(
int
num,
char
frompeg,
char
topeg,
char
auxpeg)

{

 
if
(num == 1)

 
{

     
printf
(
"\n Move disk 1 from peg %c to peg %c"
, frompeg, topeg);

     
return
;

 
}

 
towers(num - 1, frompeg, auxpeg, topeg);

 
printf
(
"\n Move disk %d from peg %c to peg %c"
, num, frompeg, topeg);

 
towers(num - 1, auxpeg, topeg, frompeg);

}

travelling saleman problem


#include<stdio.h>
#include<conio.h>
int
main()
{

int
cost[20][20],min,l,m,sr[20],sc[20],flag[20][20],i,j,k,rf[20],cf[20],n;

int
nrz[20],ncz[20],cn,a,noz,nrz1[20],ncz1[20],counter =0;

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

printf
(
"----------------------Made by C code champ-----------------\n"
);

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

printf
(
"\n\tC PROGRAM FOR TRAVELLING SALESMAN PROBLEM"
);

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

scanf
(
"%d"
,&n);

/* Enter the cost matrix*/

printf
(
"\nEnter the cost matrix\n"
);

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

{
   
printf
(
"\n"
);
   
for
(j=0;j<n;j++)
   
{
     
printf
(
"cost[%d][%d] = "
,i,j);
     
scanf
(
"%d"
,&cost[i][j]);
   
}

}

printf
(
"\n\n"
);

/* Display the entered cost matrix*/

printf
(
"Cost matrix:\n"
);

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

{
   
for
(j=0;j<n;j++)
   
printf
(
"\t%d\t"
,cost[i][j]);
   
printf
(
"\n"
);

}

/* operation on rows*/

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

{
 
min=cost[i][0];
 
/* find the minmum element in each row*/
 
for
(j=0;j<n;j++)
 
{
     
if
(min>cost[i][j])
     
min=cost[i][j];
 
}
 
/*subtract the minimum element from each element of the respective rows*/
 
for
(j=0;j<n;j++)
   
cost[i][j]=cost[i][j]-min;

}

/* operation on colums*/

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

{
 
min=cost[0][i];
 
/* find the minimum element in each column*/
 
for
(j=0;j<n;j++)
 
{
   
if
(min>cost[j][i])
     
min=cost[j][i];
 
}
 
/*subtract the minimum element from each element of the respective columns*/
 
for
(j=0;j<n;j++)
   
cost[j][i]=cost[j][i]-min;

}

printf
(
"\n\n"
);

printf
(
"Cost matrix after row & column operation:\n"
);

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

{
for
(j=0;j<n;j++)
   
printf
(
"\t%d\t"
,cost[i][j]);
 
printf
(
"\n"
);

}

repeatx:;

/*Draw minimum number of horizontal and vertical lines to cover all zeros in

resulting matrix*/

a=0;noz=0,min=1000;

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

{
for
(j=0;j<n;j++)
   
flag[i][j]=0;

}

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

{ cn=0;
 
for
(j=0;j<n;j++)
 
{
if
(cost[i][j]==0)
   
{ cn++;
 
flag[i][j]=1;
   
}
 
}
 
nrz[i]=cn;
 
noz=noz+cn;

}

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

{ cn=0;
 
for
(j=0;j<n;j++)
 
{
if
(cost[j][i]==0)
   
{ cn++;
 
flag[j][i]=1;
   
}
 
}
 
ncz[i]=cn;
 
noz=noz+cn;

}

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

{ nrz1[i]=nrz[i];
 
ncz1[i]=ncz[i];

}

k=0;

while
(nrz[k]!=0||ncz[k]!=0)

{

for
(i=0;i<n;i++)
 
{ cn=0;
 
for
(j=0;j<n;j++)
 
{
if
(flag[i][j]==1)
     
cn++;
   
nrz[i]=cn;
 
}
 
if
(nrz[i]==1)
 
{
for
(j=0;j<n;j++)
   
{
if
(flag[i][j]==1)
 
{ flag[i][j]=2;
   
for
(k=0;k<n;k++)
   
{
if
(flag[k][j]==1)
       
flag[k][j]=0;
   
}
 
}
   
}
 
}

}

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

{ cn=0;
 
for
(j=0;j<n;j++)
 
{
if
(flag[j][i]==1)
     
cn++;
   
ncz[i]=cn;
 
}
 
if
(ncz[i]==1)
 
{
for
(j=0;j<n;j++)
   
{
if
(flag[j][i]==1)
 
{ flag[j][i]=2;
   
for
(k=0;k<n;k++)
   
{
if
(flag[j][k]==1)
       
flag[j][k]=0;
   
}
 
}
   
}
 
}

}

k++;

}

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

{
for
(j=0;j<n;j++)
 
{
if
(flag[i][j]==2)
 
a++;
 
}

}


/* If minimum number of lines, a is equal to the order of the matrix n then

assignment can be optimally completed.*/

if
(a==n)

{
 
printf
(
"\nAssignments completed in order!!\n"
);
 
/* Display the order in which assignments will be completed*/
 
for
(i=0;i<n;i++)
 
{
for
(j=0;j<n;j++)
   
{
if
(flag[i][j]==2)
   
printf
(
" %d->%d "
,i+1,j+1);
   
}
   
printf
(
"\n"
);
 
}
 
getch();
 
exit
(0);

}

/* if order of matrix and number of lines is not same then its difficult to

find the optimal solution.

Now determine the smallest uncovered element i.e. element not covered by lines

and then subtract this minimum element from all uncovered elements and add the

same elements at the intersection of horizontal and vertical lines.*/

else

{
for
(i=0;i<n;i++)
 
{ rf[i]=0,sr[i]=0;
   
cf[i]=0,sc[i]=0;
 
}
 
for
(k=n;(k>0&&noz!=0);k--)
 
{
for
(i=0;i<n;i++)
   
{ m=0;
 
for
(j=0;j<n;j++)
 
{
if
((flag[i][j]==4)&&(cost[i][j]==0))
     
m++;
 
}
     
sr[i]=m;
   
}
   
for
(i=0;i<n;i++)
   
{
if
(nrz1[i]==k&&nrz1[i]!=sr[i])
 
{  rf[i]=1;
     
for
(j=0;j<n;j++)
     
{
if
(cost[i][j]==0)
         
flag[i][j]=4;
     
}
     
noz=noz-k;
 
}
   
}
   
for
(i=0;i<n;i++)
   
{
   
l=0;
   
for
(j=0;j<n;j++)
   
{
if
((flag[j][i]==4)&&(cost[j][i]==0))
     
l++;
   
}
     
sc[i]=l;
   
}
   
for
(i=0;i<n;i++)
   
{
if
(ncz1[i]==k&&ncz1[i]!=sc[i])
 
{  cf[i]=1;
     
for
(j=0;j<n;j++)
     
{
if
(cost[j][i]==0)
         
flag[j][i]=4;
     
}
     
noz=noz-k;
 
}
   
}
   
for
(i=0;i<n;i++)
   
{
for
(j=0;j<n;j++)
 
{
if
(flag[i][j]!=3)
   
{
if
(rf[i]==1&&cf[j]==1)
     
{  flag[i][j]=3;
         
if
(cost[i][j]==0)
       
noz=noz+1;
     
}
   
}
 
}
   
}
 
}
 
for
(i=0;i<n;i++)
 
{
for
(j=0;j<n;j++)
   
{
if
(rf[i]!=1&&cf[j]!=1)
 
{
if
(min>cost[i][j])
     
min=cost[i][j];
 
}
   
}
 
}
 
for
(i=0;i<n;i++)
 
{
for
(j=0;j<n;j++)
   
{
if
(rf[i]!=1&&cf[j]!=1)
   
cost[i][j]=cost[i][j]-min;
   
}
 
}
 
for
(i=0;i<n;i++)
 
{
for
(j=0;j<n;j++)
   
{
if
(flag[i][j]==3)
   
cost[i][j]=cost[i][j]+min;
   
}
 
}

}

printf
(
"\n\n"
);

if
(counter < 10)

{
 
counter = counter+1;

printf
(
"\n\nIntermediate Matrix: \n"
);

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

{        
 
for
(j=0;j<n;j++)
 
printf
(
"\t%d\t"
,cost[i][j]);
 
printf
(
"\n"
);

}

}

else

{
   
printf
(
"\n\nOptimal solution to given problem is not possible"
);
   
getch();
   
return
0;
   
}

goto
repeatx;
}

Tuesday 27 October 2015

C Program Source Code for the Longest Common Subsequence problem

#include<stdio.h>
#include<string.h>
#define maxn 100100
int max(int a,int b)
{
        return a>b?a:b;
}
int LongestCommonSubsequence(char S[],char T[])
{
        int Slength = strlen(S);
        int Tlength = strlen(T);
        /* Starting the index from 1 for our convinience (avoids handling special cases for negative indices) */
        int iter,jter;
        for(iter=Slength;iter>=1;iter--)
        {
                S[iter] = S[iter-1];
        }
        for(iter=Tlength;iter>=1;iter--)
        {
                T[iter] = T[iter-1];
        }
        int common[Slength+1][Tlength+1];
        /* common[i][j] represents length of the longest common sequence in S[1..i], T[1..j] */
        /* Recurrence:  common[i][j] = common[i-1][j-1] + 1 if S[i]==T[j]
                                     = max(common[i-1][j],common[i][j-1]) otherwise
        */    
        /*common[0][i]=0, for all i because there are no characters from string S*/
        for(iter=0;iter<=Tlength;iter++)
        {
                common[0][iter]=0;
        }
        /*common[i][0]=0, for all i because there are no characters from string T*/
        for(iter=0;iter<=Slength;iter++)
        {
                common[iter][0]=0;
        }
        for(iter=1;iter<=Slength;iter++)
        {
                for(jter=1;jter<=Tlength;jter++)
                {
                        if(S[iter] == T[jter] )
                        {
                                common[iter][jter] = common[iter-1][jter-1] + 1;
                        }
                        else
                        {
                                common[iter][jter] = max(common[iter][jter-1],common[iter-1][jter]);
                        }

                }
        }
        return common[Slength][Tlength];

}
int main()
{
        char S[maxn],T[maxn];/* S,T are two strings for which we have to find the longest common sub sequence. */
        scanf("%s%s",S,T);
        printf("%d\n",LongestCommonSubsequence(S,T));

}


try this awesome hacking tutorial

Sunday 13 September 2015

linear search

#include <stdio.h>

int main()
{
   int array[100], search, c, n;

   printf("Enter the number of elements in array\n");
   scanf("%d",&n);

   printf("Enter %d integer(s)\n", n);

   for (c = 0; c < n; c++)
      scanf("%d", &array[c]);

   printf("Enter the number to search\n");
   scanf("%d", &search);

   for (c = 0; c < n; c++)
   {
      if (array[c] == search)     /* if required element found */
      {
         printf("%d is present at location %d.\n", search, c+1);
         break;
      }
   }
   if (c == n)
      printf("%d is not present in array.\n", search);

   return 0;
}

sequential search

#include <stdio.h>

int main()
{
   int array[100], search, c, n;

   printf("Enter the number of elements in array\n");
   scanf("%d",&n);

   printf("Enter %d integer(s)\n", n);

   for (c = 0; c < n; c++)
      scanf("%d", &array[c]);

   printf("Enter the number to search\n");
   scanf("%d", &search);

   for (c = 0; c < n; c++)
   {
      if (array[c] == search)     /* if required element found */
      {
         printf("%d is present at location %d.\n", search, c+1);
         break;
      }
   }
   if (c == n)
      printf("%d is not present in array.\n", search);

   return 0;
}

Monday 7 September 2015

to find root of quadratic equation

#include <stdio.h>
#include <math.h>
int main()
{
  float a, b, c, determinant, r1,r2, real, imag;
  printf("Enter coefficients a, b and c: ");
  scanf("%f%f%f",&a,&b,&c);
  determinant=b*b-4*a*c;
  if (determinant>0)
  {
      r1= (-b+sqrt(determinant))/(2*a);
      r2= (-b-sqrt(determinant))/(2*a);
      printf("Roots are: %.2f and %.2f",r1 , r2);
  }
  else if (determinant==0)
  {
    r1 = r2 = -b/(2*a);
    printf("Roots are: %.2f and %.2f", r1, r2);
  }
  else
  {
    real= -b/(2*a);
    imag = sqrt(-determinant)/(2*a);
    printf("Roots are: %.2f+%.2fi and %.2f-%.2fi", real, imag, real, imag);
  }
  return 0;
}

bricks game project

Bricks game in C

#include <iostream.h>
#include <conio.h>
#include <ctype.h>
# include <process.h>
# include <dos.h>
# include <stdlib.h>
# include <graphics.h>
# include <stdio.h>

# define NULL 0
# define YES 1
# define NO 0
#define ESC 0x1b /* Define the escape key */

int MaxX, MaxY, MidX, MidY ;
int bri[5][20] ;

int    GraphDriver; /* The Graphics device driver */
int    GraphMode; /* The Graphics mode value */
double AspectRatio; /* Aspect ratio of a pixel on the screen*/
int    MaxXX, MaxYY; /* The maximum resolution of the screen */
int    MaxColors; /* The maximum # of colors available */
int    ErrorCode; /* Reports any graphics errors */
struct palettetype palette; /* Used to read palette info*/

// Initialize the graphics mode
void Initialize(void);

// Display the last screen of bricks
void SayGoodbye(void);

// Establish the main window for the demo
void MainWindow(char *header);

// Display the message Press any key to continue at last screen
void StatusLine(char *msg);

// Draws a boarder line at last screen
void DrawBorder(void);

// Changes the text style
void changetextstyle(int font, int direction, int charsize);

// Welcome screen of bricks game
mainscreen();

// Instruction messages of bricks game
screen();

// To display the bricks (in square box) and paddles in rectangle form and
bulbs rounded form
bricks();

// Delete a bricks when bulb hit it
delbrick(int,int);

// Echoes different musics
bell(int);

int graphmode = CGAHI, graphdriver = CGA, level;

main
()
{
union REGS ii, oo ;

int BallX, BallY, Base1, Base2, dx = 1, dy = -1, OldX, OldY ;
int totallayer[5] = { 10, 20, 30, 40, 50 }, max = 50, layer = 4 ;
int i, flag = 0, speed = 25, score = 0, chance = 4, areareq ;

char *m1, *m2 ;

/* Function to initialise the graphics mode */
initgraph ( &graphdriver, &graphmode, "c:\tc\bgi " ) ;
mainscreen();
initgraph ( &graphdriver, &graphmode, "c:\tc\bgi " ) ;
/* get the maximum value of x and y coordinates of the screen */
MaxX = getmaxx() ;
MaxY = getmaxy() ;
/* finding the center of the screen */
MidX = MaxX / 2 ;
MidY = MaxY / 2 ;


/* create opening  screen and accept the level of the  player's  */
level = screen() ;

/* assign the  speed to ball as per the level chosen */
switch ( level )
{
case 'M' :
case 'm' :
speed = 15 ;
break ;

case 'F' :
case 'f' :
speed = 10 ;
}

/* draw the four layer of bricks, the paddle and the ball */
rectangle ( 0, 0, MaxX, MaxY - 12 ) ;
bricks() ;
rectangle ( MidX - 25, MaxY - 7 - 12, MidX + 25, MaxY - 12 ) ;
floodfill ( MidX, MaxY - 1 - 12, 12 ) ;
circle ( MidX, MaxY - 13 - 12, 12 ) ;
floodfill ( MidX, MaxY - 10 - 12, 12 ) ;

/* memory allocation for storing the image of the paddle */
areareq = imagesize ( MidX - 12, MaxY - 18, MidX + 12, MaxY - 8 ) ;
m1 =((char*) malloc ( areareq )) ;

/* memory allocation for storing the image of the ball */
areareq = imagesize ( MidX - 25, MaxY - 7, MidX + 25, MaxY - 1 ) ;
m2 =((char *) malloc ( areareq ) );

/* if unable to alloacte the memory  */
if ( m1 == NULL || m2 == NULL )
{
puts ( "Not Enough memory!!" ) ;
exit ( 1 ) ;
}

/* image of the paddle and the ball is stored into allocated memory */
getimage ( MidX - 12, MaxY - 7 - 12 - 12 + 1, MidX + 12, MaxY - 8 - 12,
m1 ) ;
getimage ( MidX - 25, MaxY - 7 - 12, MidX + 25, MaxY - 1 - 12, m2 ) ;

/* store current position of the paddle and ball */
Base1 = MidX - 25 ;
Base2 = MaxY - 7 - 12 ;
BallX = MidX - 12 ;
BallY = MaxY - 7 - 12 + 1 - 12 ;

/* display balls remaining ( initially 3 ) */
gotoxy ( 45, 25 ) ;
cout<< "Balls :"  ;
for ( i = 0 ; i < 3 ; i++ )
{
circle ( 515 + i * 35, MaxY - 5, 12 ) ;
floodfill ( 515 + i * 35, MaxY - 5, 12 ) ;
}

/* display starting score */
gotoxy ( 1, 25 ) ;
cout<< "Score:   ";
gotoxy(16,25);
cout<<score;

/* select font and alignment for displaying text */
settextjustify ( CENTER_TEXT, CENTER_TEXT ) ;
changetextstyle ( GOTHIC_FONT, HORIZ_DIR, 4 ) ;

while ( 1 )
{
flag = 0 ;

/* saving current x and y coordinates of the ball */
OldX = BallX ;
OldY = BallY ;

/* update ballx and bally to move the ball in correct direction */
BallX = BallX + dx ;
BallY = BallY + dy ;

/* according to the position of ball the layer of bricks is determined
*/
if ( BallY > 40 )
{
max = 50 ;
layer = 4 ;
}
else
{
if ( BallY > 30 )
{
max = 40 ;
layer = 3 ;
}
else
{
if ( BallY > 20 )
{
max = 30 ;
layer = 2 ;
}
else
{
if ( BallY > 10 )
{
max = 20 ;
layer = 1 ;
}
else
{
max = 10 ;
layer = 0 ;
}
}
}
}

/* if the ball hits the right boundary, move it to the left */
if ( BallX > ( MaxX - 24 - 1 ) )
{
bell ( 5 ) ;
BallX = MaxX - 24 - 1 ;
dx = -dx ;
}

/* if the ball hits the left boundary, move it to the right */
if ( BallX < 1 )
{
bell ( 5 ) ;
BallX = 1 ;
dx = -dx ;
}

/* if the ball hits the top boundary, move it down */
if ( BallY < 1 )
{
bell (  5 ) ;
BallY = 1 ;
dy = -dy ;
}

/* if the ball is in the area of the bricks */
if ( BallY < max )
{
/* if there is no brick  at the top of the ball */
if ( bri[layer][ ( BallX + 10 ) / 32 ] == 1 )
{
/*  if the ball touches a brick */
for ( i = 1 ; i <= 6 ; i++ )
{
/* check whether there is a brick to the right of the ball */
if ( bri[layer][ ( BallX + i + 10 ) / 32 ] == 0 )
{
/* if there is a brick */
BallX = BallX + i ;
flag = 1 ;
break ;
}

/* check whether there is a brick to the left of the ball */
if ( bri[layer][ ( BallX - i + 10 ) / 32 ] == 0 )
{
BallX = BallX - i ;
flag = 1 ;
break ;
}
}

/* if the ball does not touch a brick at the top, left or right */
if ( !flag )
{
/* check if the ball has moved above the current layer */
if ( BallY < totallayer[layer - 1] )
{
/* if so, change current layer appropriately */
layer-- ;
max = totallayer[layer] ;
}

/* restore the image of the ball at the old coordinates */
putimage ( OldX, OldY, m1, OR_PUT ) ;

/* erase the image at the old coordinates */
putimage ( OldX, OldY, m1, XOR_PUT ) ;

/* place the image of the ball at the new coordinates */
putimage ( BallX, BallY, m1, XOR_PUT ) ;

/*  delay for fewseconds*/
delay ( speed ) ;

/* carry on moving the ball */
continue ;
}
}

/* when ball touch the brick control comes to this point */
bell ( 5 ) ;  /* play music */

/* erase the touched brick  */
delbrick ( ( BallX + 10 ) / 32, layer ) ;

/* if the brick hit is on the extreme right */
if ( ( BallX + 10 ) / 32 == 19 )
line ( MaxX, 0, MaxX, 50 ) ;  /* redraw right boundary */

/* if the brick hit is on the extreme left */
if ( ( BallX + 10 ) / 32 == 0 )
line ( 0, 0, 0, 50 ) ;  /* redraw left boundary */

/* if the brick hit is in the topmost layer */
if ( layer == 0 )
line ( 0, 0, MaxX, 0 ) ;  /* redraw top boundary */

/* set appropriate array element to 1 to indicate absence of brick */
bri[layer][ ( BallX + 10 ) / 32 ] = 1 ;

BallY = BallY + 1 ;  /* update the y coordinate */
dy = -dy ;  /* change the current direction of the ball */
score += 10 ;  /* increment the score by 10 */
gotoxy ( 16, 25 ) ;
cout<< score;  /* display latest score */

/* if the first brick is hit during a throw*/
}


/* if  ball reached the bottom */
if ( BallY > 180 - 12 )
{

/* if paddle missed the ball */
if ( BallX < Base1 - 20 || BallX > Base1 + 50 )
{
/* continue the decrement of the ball */
while ( BallY < 177 )
{
/* erase the image of the ball at the old coordinates */
putimage ( OldX, OldY, m1, XOR_PUT ) ;

/* put the image of the ball at the new coordinates */
putimage ( BallX, BallY, m1, XOR_PUT ) ;

/* introduce delay for fewseconds */
delay ( speed ) ;

/* saveing current x and y coordinates of the ball */
OldX = BallX ;
OldY = BallY ;

/* update ballx and bally to move the ball in correct direction */
BallX = BallX + dx ;
BallY = BallY + dy ;
}

chance-- ;  /* decrement the total number of chances */
score -= 10 ;  /* decrement 10 points for each ball lost */
gotoxy ( 16, 25 ) ;
cout<< score;  /* display latest score */
bell ( 1 ) ;

/* erase one  of the available balls */
if ( chance )
putimage ( 515 + ( chance - 1 ) * 35 - 12 , MaxY - 10, m1, XOR_PUT )
;

/* if the last ball is being played */
if ( chance == 1 )
{
gotoxy ( 45, 25 ) ;
cout<< "Last ball... careful!";
}

/* if all the balls are lost */
if ( !chance )
{
gotoxy ( 45, 25 ) ;
cout<<"Press any key to continue ...              " ;
outtextxy ( MidX, MidY, "Better luck next time" ) ;
bell ( 2 ) ;

closegraph() ;
restorecrtmode() ;
closegraph(); /* Close the graphics mode */
Initialize(); /* Intialize the graphics mode */
setbkcolor(4);
SayGoodbye(); /* Display the That's all Folks message */
closegraph(); /* Return the system to text mode */
exit ( 0 ) ;
}
}

/* if ball is collected on paddle */
bell ( 4 ) ;
BallY = 180 - 12 ;  /* restore the y coordinate of ball */
dy = -dy ;  /* move the ball upwards */
}

/* put the image of the ball at the old coordinates */
putimage ( OldX, OldY, m1, OR_PUT ) ;

/* erase the image of the ball at the old coordinates */
putimage ( OldX, OldY, m1, XOR_PUT ) ;

/* put the image of the ball at the upadted coordinates */
putimage ( BallX, BallY, m1, XOR_PUT ) ;

/* if all the bricks have been knockout */
if ( score == 500 - ( ( 4 - chance ) * 20 ) )
{
outtextxy ( MidX, MidY, "Winner !!" ) ;

if ( score < 600 )
outtextxy ( MidX, MidY + 30, "Try to score 600" ) ;
else
outtextxy ( MidX, MidY + 30, " GREAT!" ) ;

bell ( 2 ) ;

closegraph() ;
restorecrtmode() ;
exit ( 0 ) ;
}

/* introduce delay for few seconds */
delay ( speed ) ;

/* if the key is pressed to move the paddle */
if ( kbhit() )
{
/* interrupt issue to obtain the ascii and scan codes of key hit */
ii.h.ah = 0 ;
int86 ( 22, &ii, &oo ) ;

/* put the image of the paddle at the old coordinates */
putimage ( Base1, Base2, m2, OR_PUT ) ;

/* erase the image of the paddle at the old coordinates */
putimage ( Base1, Base2, m2, XOR_PUT ) ;

/* if Esc key has been pressed */
if ( oo.h.ah == 1 )
exit ( 0 ) ;

/* right arrow key */
if ( oo.h.ah == 75 )
Base1 = Base1 - 25 ;

/* left arrow key */
if ( oo.h.ah == 77 )
Base1= Base1 + 25 ;

/* if paddle goes beyond left boundary */
if ( Base1 < 0 )
Base1 = 0 ;

/* if paddle goes beyond right boundary */
if ( Base1 > 589 )
Base1 = 589 ;

/* put the image of the paddle at the proper position */
putimage ( Base1, Base2, m2, XOR_PUT ) ;
}

}
closegraph();
Initialize();
SayGoodbye(); /* Give user the closing screen */
closegraph(); /* Return the system to text mode */
return(0);
}

/* This function creates the opening screen and
displyed instruction related to the game */

screen()
{
int i, j, lx = 0, ly = 0, ch ;


rectangle(1,1,600,195);
setbkcolor(4);
/* set the textstyle for displaying instruction */
changetextstyle ( DEFAULT_FONT, HORIZ_DIR, 0 ) ;
outtextxy ( 150, 55, "         Instructions        " ) ;
changetextstyle (4, HORIZ_DIR, 5 );
outtextxy ( 130, 0, " B R I C K S" ) ;
changetextstyle ( DEFAULT_FONT, HORIZ_DIR, 0 ) ;
outtextxy ( 30, 68, "Use left and right arrow keys to move paddle." ) ;
outtextxy ( 30, 88, "If you don't collect the ball on the paddle, you
lose the ball." ) ;
outtextxy ( 30, 108, "On loosing a ball you loose 20 points." ) ;
outtextxy ( 30, 128, "On taking a brick you gain 5 points." ) ;
changetextstyle(7, HORIZ_DIR, 3);
outtextxy ( 100, 148, "Press any key to continue ..." ) ;
bell ( 3 ) ;  /* ring music */
fflush ( stdin ) ;
if ( getch() == 0 )
getch() ;

  closegraph();
  initgraph ( &graphdriver, &graphmode, "c:\tc\bgi " ) ;
  rectangle(2,2,620,195);
  setbkcolor(4);
/* display the main menu */
while ( 1 )
{

changetextstyle(4,HORIZ_DIR,5);
outtextxy ( 60, 8, "Options Available:" ) ;
outtextxy ( 150, 55, "Play ( P )" ) ;
outtextxy ( 150, 125, "Exit ( E )" ) ;

ch = 0 ;

/* continue untill you select the correct choice  */
while ( ! ( ch == 'E' ||   ch == 'P' ) )
{
fflush ( stdin ) ;

/* if a special key is hit, flush the keyboard buffer */
if ( ( ch = getch() ) == 0 )
getch() ;
else
ch = toupper ( ch ) ;    /* store the uppercase of the choice made*/
}

if ( ch == 'P' )
break ;
if (ch == 'E')
exit ( 0 ) ;

}

setviewport ( 1, 125 - 12, MaxX - 1, MaxY - 1, 1 ) ;
clearviewport() ;
closegraph();
initgraph ( &graphdriver, &graphmode, "c:\tc\bgi " ) ;
rectangle(2,2,620,195);
setbkcolor(4);

/* display menu for the diffrent levels */
changetextstyle(7,HORIZ_DIR,3);
outtextxy ( 60, 8, "Select the level for play:" ) ;
outtextxy ( 150,50, "Slow ( S )" ) ;
outtextxy ( 150, 100, "Medium ( M )" ) ;
outtextxy ( 150, 150, "Fast ( F )" ) ;

/* accept user's choice */
fflush ( stdin ) ;
if ( ( ch = getch() ) == 0 )
getch() ;

clearviewport() ;

/* return the choice selected by the user */
return ( ch ) ;
}

/* This function draws bricks at the start of the game.There are four
layers of
the bricks  */
bricks()
{
int i, j, lx = 0, ly = 0 ;

for ( i = 0 ; i < 5 ; i++ )  /* 5 rows */
{
for ( j = 0 ; j < 30 ; j++ )  /* 20 columns */
{
/* draw a brick at appropriate coordinates */
rectangle ( lx, ly, lx + 20, ly + 7 ) ;
floodfill ( lx + 1, ly + 1, 2 ) ;

lx = lx + 32 ;
}

lx = 0 ;
ly = ly + 10 ;
}
}


/* This function erases the  brick which is knock by the ball */
delbrick ( int b, int l )
{
/* b - brick number, l - layer */

setcolor ( BLACK ) ;
rectangle ( b * 32, l * 10, ( b * 32 ) + 20 , ( l * 10 ) + 7 ) ;
rectangle ( b * 32 + 1, l * 10, ( b * 32 ) + 20 - 1, ( l * 10 ) + 7 - 1 )
;
rectangle ( b * 32 + 2, l * 10, ( b * 32 ) + 20 - 2, ( l * 10 ) + 7 - 2 )
;
rectangle ( b * 32 + 3, l * 10, ( b * 32 ) + 20 - 3, ( l * 10 ) + 7 - 3 )
;
rectangle ( b * 32 + 4, l * 10, ( b * 32 ) + 20 - 4, ( l * 10 ) + 7 - 4 )
;
rectangle ( b * 32 + 5, l * 10, ( b * 32 ) + 20 - 5, ( l * 10 ) + 7 - 5 )
;
rectangle ( b * 32 + 6, l * 10, ( b * 32 ) + 20 - 6, ( l * 10 ) + 7 - 6 )
;
setcolor ( CGA_YELLOW ) ;
}

/* plays different types of music */
bell ( int m_no )
{
/* natural frequencies of 7 notes */
float wave[6] = { 120.81, 136.83, 144.81, 154.61, 216, 240 } ;
int n, i ;

switch ( m_no )
{
case 1 :
for ( i = 0 ; i < 6 ; i++ )
{
sound ( wave[i] * 1 ) ;
delay ( 30 ) ;
}
nosound() ;
break ;

case 2 :
for ( i = 0 ; i < 15 ; i++ )
{
n = random ( 6 ) ;
sound ( wave[n] * 2 ) ;
delay ( 100 ) ;
}
nosound() ;
break ;

case 3 :
while ( !kbhit() )
{
n = random ( 6 ) ;
sound ( wave[n] * 2 ) ;
delay ( 100 ) ;
}
nosound() ;

/* flush the keyboard buffer */
if ( getch() == 0 )
getch() ;

break ;

case 4 :
for ( i = 5 ; i >= 0 ; i-- )
{
sound ( wave[i] * 4 ) ;
delay ( 15 ) ;
}
nosound() ;
break ;

case 5 :
sound ( wave[2] * 5 ) ;
delay ( 50 ) ;
nosound() ;
}
}
/* */
/* INITIALIZE: Initializes the graphics system and reports */
/* any errors which occured. */
/* */

void Initialize(void)
{
  int xasp, yasp; /* Used to read the aspect ratio*/

  GraphDriver = DETECT; /* Request auto-detection */
  initgraph( &GraphDriver, &GraphMode, "c:\tc\bgi" );
  ErrorCode = graphresult(); /* Read result of initialization*/
  if( ErrorCode != grOk ){ /* Error occured during init */
printf(" Graphics System Error: %s
", grapherrormsg( ErrorCode ) );
exit( 1 );
  }

  getpalette( &palette ); /* Read the palette from board */
  MaxColors = getmaxcolor() + 1; /* Read maximum number of colors*/

  MaxXX = getmaxx();
  MaxYY = getmaxy(); /* Read size of screen */

  getaspectratio( &xasp, &yasp ); /* read the hardware aspect */
  AspectRatio = (double)xasp / (double)yasp; /* Get correction factor */

}
/* */
/* SAYGOODBYE: Give a closing screen to the user before leaving. */
/* */

void SayGoodbye(void)
{
  struct viewporttype viewinfo; /* Structure to read viewport */
  int h, w;

  MainWindow( "== Finale ==" );

  getviewsettings( &viewinfo ); /* Read viewport settings */
  changetextstyle( TRIPLEX_FONT, HORIZ_DIR, 4 );
  settextjustify( CENTER_TEXT, CENTER_TEXT );

  h = viewinfo.bottom - viewinfo.top;
  w = viewinfo.right  - viewinfo.left;
  outtextxy( w/2, h/2, "That's all, folks!" );

  StatusLine( "Press any key to EXIT" );
  getch();

  cleardevice(); /* Clear the graphics screen */

}

/* */
/* MAINWINDOW: Establish the main window for the demo and set */
/* a viewport for the demo code. */
/* */

void MainWindow( char *header )
{
  int height;

  cleardevice(); /* Clear graphics screen */
  setcolor( MaxColors - 1 ); /* Set current color to white */
  setviewport( 0, 0, MaxXX, MaxYY, 1 ); /* Open port to full screen */

  height = textheight( "H" );           /* Get basic text height        */

  changetextstyle( DEFAULT_FONT, HORIZ_DIR, 1 );
  settextjustify( CENTER_TEXT, TOP_TEXT );
  outtextxy( MaxXX/2, 2, header );
  setviewport( 0, height+4, MaxXX, MaxYY-(height+4), 1 );
  DrawBorder();
  setviewport( 1, height+5, MaxXX-1, MaxYY-(height+5), 1 );

}

/* */
/* STATUSLINE: Display a status line at the bottom of the screen. */
/* */

void StatusLine( char *msg )
{
  int height;

  setviewport( 0, 0, MaxXX, MaxYY, 1 ); /* Open port to full screen */
  setcolor( MaxColors - 1 ); /* Set current color to white */

  changetextstyle( DEFAULT_FONT, HORIZ_DIR, 1 );
  settextjustify( CENTER_TEXT, TOP_TEXT );
  setlinestyle( SOLID_LINE, 0, NORM_WIDTH );
  setfillstyle( EMPTY_FILL, 0 );

  height = textheight( "H" );           /* Detemine current height      */
  bar( 0, MaxYY-(height+4), MaxXX, MaxYY );
  rectangle( 0, MaxYY-(height+4), MaxXX, MaxYY );
  outtextxy( MaxXX/2, MaxYY-(height+2), msg );
  setviewport( 1, height+5, MaxXX-1, MaxYY-(height+5), 1 );

}

/* */
/* DRAWBORDER: Draw a solid single line around the current */
/* viewport. */
/* */

void DrawBorder(void)
{
  struct viewporttype vp;

  setcolor( MaxColors - 1 ); /* Set current color to white */

  setlinestyle( SOLID_LINE, 0, NORM_WIDTH );

  getviewsettings( &vp );
  rectangle( 0, 0, vp.right-vp.left, vp.bottom-vp.top );

}

/* */
/* CHANGETEXTSTYLE: similar to settextstyle, but checks for */
/* errors that might occur whil loading the font file. */
/* */

void changetextstyle(int font, int direction, int charsize)
{
  int ErrorCode;

  graphresult(); /* clear error code */
  settextstyle(font, direction, charsize);
  ErrorCode = graphresult(); /* check result */
  if( ErrorCode != grOk ){ /* if error occured */
closegraph();
printf(" Graphics System Error: %s
", grapherrormsg( ErrorCode ) );
exit( 1 );
  }
}

/* The main function body of main screen which displays the main screen
creating the opening screen display */
mainscreen()
{
int maxx, maxy, in, area;

// get maximum x, y coordinates of the screen
maxx = getmaxx();
maxy = getmaxy();

// setbkcolor sets the current background color using the palette
setbkcolor(RED);

// Draws a rectangle (graphics mode)
rectangle(0, 0, maxx, maxy);

// sets the line style and text justification in screen
changetextstyle(1, HORIZ_DIR, 0);

// displaying the output text on main screen
outtextxy(220, 20, "WELCOME");
outtextxy(240,60,"   TO ");
outtextxy(220,100," BRICKS");
changetextstyle(7, HORIZ_DIR, 3);
bell(3);
outtextxy(110, 150, "Press any key to continue...");

// Flushes the standard input device
fflush(stdin);
getch();
closegraph();

}