Saturday 15 March 2014

Code for Program to get string after user specified position in C Programming

Code for Program to get string after user specified position in C Programming


//xstrchr() fn.


#include <stdio.h>
#include <conio.h>

void main(){
     char * xstrchr(char *,char);
     charstring[15];
     char *ptr,c;
    clrscr();
    printf("Enter a string : ");
    scanf("%[^\n]s",string);
    printf("Enter search character : ");
    flushall();
    scanf("%c",&c);
    ptr = xstrchr(string, c);
    printf("\nOutput of function is : %s\n",ptr);
    if (ptr)
       printf("The character %c is at position: %d\n", c, ptr-string);
    else
       printf("The character was not found\n");
    getch();
}

char * xstrchr(char *str,char ch){
       int i;
       for(i=0;str[i];i++){
       if(str[i]==ch)
          return ((str+i)+1);
       }
       return(0);
}

FIND VALUE OF X1 AND X2 WHICH IS SOLUTION OF LINEAR EQUATION

PROGRAM TO FIND VALUE OF X1 AND X2 WHICH IS SOLUTION OF LINEAR EQUATION

Code for PROGRAM TO FIND VALUE OF X1 AND X2 WHICH IS SOLUTION OF LINEAR EQUATION in C Programming

#include<stdio.h>
#include<conio.h>

void main()
{
    int a,b,c,d,m,n;
    float x1,x2;
    clrscr();

    printf("Enter the value of a ::  ");
    scanf("%d",&a);

    printf("Enter the value of b ::  ");
    scanf("%d",&b);

    printf("Enter the value of c ::  ");
    scanf("%d",&c);

    printf("Enter the value of d ::  ");
    scanf("%d",&d);

    printf("Enter the value of m ::  ");
    scanf("%d",&m);

    printf("Enter the value of n ::  ");
    scanf("%d",&n);

    if((a*d)-(c*b) == 0)
    printf("\nWe can't find value of x1 and x2 \n");
    else
    {
        x1 = (float)((m * d) - (b * n)) / ((a * d) - (c * b));
        printf("\nValue of x1 ::  %f ",x1);
        x2 = (float)((n * a) - (m * c)) / ((a * d) - (c * b));
        printf("\nValue of x2 ::  %f ",x2);

    }
    getch();
}
/*
    ********
     OUTPUT
    ********
    Enter the value of a ::  5
    Enter the value of b ::  2
    Enter the value of c ::  5
    Enter the value of d ::  3
    Enter the value of m ::  6
    Enter the value of n ::  7

    Value of x1 ::  0.800000
    Value of x2 ::  1.000000
*/

ode for Program to search and/or replace a word in C Program in C Programming

Write a program to search and/or replace a word in C Program. It asks for an input file and 2 string. One for searching and one for replacement.If the file contains search string than it will print that line containing search string and asks for the confirmation to change it.If you say "yes" it changes it else continues till the file is over.

Code for Program to search and/or replace a word in C Program in C Programming

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

count_data();

void main()
{
   // calling function
   count_data();
   getch();
}
count_data() // function for count no of words,lines & characters.
{
   FILE *fp,*fp_rep;
   char ch,ch1,temp_str[50],rep_str[10],new_str[10];
   int count=0; // counter
   clrscr();


   fp=fopen("c:\\windows\\desktop\\input.txt","r");
   fp_rep=fopen("c:\\windows\\desktop\\input1.txt","w");

   printf("\nEnter String to find:");
   scanf("%s",rep_str);
   printf("\nEnter String to replace:");
   scanf("%s",new_str);

   while((ch=getc(fp))!=EOF)
   {
     if(ch==' ')
      {
    temp_str[count]='\0';
    if(strcmp(temp_str,rep_str)==0)
     {
      printf("Do u want to replace(y/n):");
      ch1=getche();
      if(ch1=='y')
      {
       fprintf(fp_rep," %s",new_str);
       count=0;
      }
      else
       { fprintf(fp_rep," %s",temp_str);count=0;}
     }
    else
     {
       fprintf(fp_rep," %s",temp_str);
       count=0;
      }
      }else
      {
    temp_str[count++]=ch;
      }
    }
      if(strcmp(temp_str,rep_str)==0)
     {

      printf("Do u want to replace(y/n):");
      ch1=getche();
      if(ch1=='y')
      {
       fprintf(fp_rep,"%s ",new_str);
       count=0;
      }
      else
       {
        fprintf(fp_rep,"%s ",temp_str);
        count=0;
       }
     }else
      {
       fprintf(fp_rep,"%s ",temp_str);
      }

    fclose(fp);
    fclose(fp_rep);
    remove("c:\\windows\\desktop\\input.txt");
    rename("c:\\windows\\desktop\\input1.txt","c:\\windows\\desktop\\input.txt");
    fflush(stdin);

}

Write a program to sort a list in alphabatic order using pointers.

Write a program to sort a list in alphabatic order using pointers.

Code for Program to sort a list in alphabatic order using pointers in C Programming

#include <stdio.h>
#include <conio.h>
#include <math.h>
#include <alloc.h>
void main()
{

char *a[10],dum[10],s;
int i,k,j,n;
clrscr();
printf("enter the no of std....");
scanf("%d",&n);
printf("enter the name of students ");
for(k=0;k<n;k++)
scanf("%s",a[k]);
for(i=1;i<n;i++)
{
for(j=1;j<n-i;j++)
{if(strcmp(a[j-1],a[j])>0)
  {strcpy(*dum,*a[j-1]);
   strcpy(*a[j-1],*a[j]);
   strcpy(*a[j],*dum);
 }
 }  }
 for(i=0;i<n;i++)
 printf("%s",a[i]);
 getch();
 }

Write a program of hanoi tower.

Write a program of hanoi tower.

Code for Program of hanoi tower in C Programming

#include<stdio.h>
#include<conio.h>

void main()
{
  int n;
  int hanoi(int,char,char,char);
  clrscr();
  printf("Enter  the no of disk:");
  scanf("%d",&n);
  hanoi(n,'a','b','c');
  getch();
}
int hanoi(int n,char a, char b, char c)
{
while(n!=0)
{
hanoi(n-1,a,c,b);
printf("Moving disk %d from %c tower to %c tower\n",n,a,c);
hanoi(n-1,b,a,c);
break;
}
return 0;

}

Example of using preprocessor - 4 in different files.

Example of using preprocessor - 4 in different files.

Code for Example of using preprocessor - 4 in different files in C Programming

//file1.h#define USD 1

//file2.h#define UKP 1

//file3
#include <stdio.h>
#include <file1.h>               //A#if !defined (USD) || !defined (UKP)      // B#error “ERROR: NO_CURRENCY rate is specified.”  //C#endif

 main()
{        
    int rs;
    rs = 10 * currency_rate;          //D
    printf (“%d\n”, rs);
}

Write a program to calculate range of v

Write a program to calculate range of v
Code for Program to calculate range of values in C Programmingalues.

main()                                                      
   {                                                           
       int count;                                                   
       floatvalue, high, low, sum, average, range;                              
       sum = 0;                                                
       count = 0;                                              
       printf("Enter numbers in a line :                       
                 input a NEGATIVE number to end\n");           
   input:                                                      
       scanf("%f", &value);                                    
       if (value < 0) goto output;                             
          count = count + 1;                                   
       if (count == 1)                                         
          high = low = value;                                  
       elseif (value > high)                                  
               high = value;                                   
            elseif (value < low)                              
                 low = value;  
      sum = sum + value;                                       
      goto input;  

                                            
   output:                                                     
      average = sum/count;                                         
      range = high - low;                                      
      printf("\n\n");                                          
      printf("Total values : %d\n", count);                    
      printf("Highest-value: %f\nLowest-value : %f\n",         
               high, low);                                     
      printf("Range        : %f\nAverage      : %f\n",         
               range, average);                                
   }                                                           
                                                               
   
Output                                                      


                                                               
   Enter numbers in a line : input a NEGATIVE number to end    
   35  40.50  25  31.25  68.15  47  26.65  29  53.45  62.50 -1 
                                                               
   Total values : 10                                           
   Highest-value: 68.150002                                    
   Lowest-value : 25.000000                                    
   Range        : 43.150002                                    
   Average      : 41.849998 

Sunday 9 March 2014

A car garage simulation using de-queue (link list implementation).

A car garage simulation using de-queue (link list implementation).

Code for A car garage simulation using de-queue (link list implementation) in C Programming

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

#define TOP 1
#define BOT 2

struct node
{
    char plate [15] ;
    struct node *link ;
} *front[5], *rear[5] ;

char plate[15], temp[15] ;
int i ;

void add_dq ( struct node**, struct node**, int, char* ) ;
char* del_dq ( struct node**, struct node**, int ) ;
void push ( struct node**, char* ) ;
char* pop ( struct node** ) ;
void q_display ( struct node * ) ;

void main( )
{
    char ad ;
    int s, lane = -1, min, lc ;

    clrscr( );
    while ( 1 )
    {
        for ( i = 0 ; i < 5 ; i++ )
        {
            printf( "lane %d: ", i ) ;
            q_display ( front[i] ) ;
        }

        printf( "\nArrival/Departure/Quit? ( A/D/Q ): " ) ;
        ad = getch( ) ;

        if ( toupper ( ad ) == 'Q' )
            exit ( 1 ) ;

        printf ( "\nEnter license plate num:" ) ;
        gets ( plate ) ;
        ad = toupper ( ad ) ;

        if ( ad == 'A' )  /* arrival of car */

        {
            lane = -1 ;  /* assume no lane is available */

            min = 10 ;
            for ( i = 0 ; i < 5 ; i++ )
            {
                s = count ( front[i] ) ;
                if ( s < min )
                {
                    min = s ;
                    lane = i ;
                }
            }

            if ( lane == -1 )
                printf ( "\nNo room available" ) ;
            else
            {
                add_dq ( &front[ lane ], &rear[ lane ], BOT, plate ) ;
                printf ( "\npark car at lane %d slot %d\n", lane, s ) ;
            }
        }
        else
        {
            if ( ad == 'D' )  /* departure of car */

            {
                for ( i = 0 ; i < 5 ; ++i )
                {
                    s = search ( front[i], plate ) ;
                    if ( s != -1 )
                    {
                        lane = i ;
                        break ;
                    }
                }
                if ( i == 5 )
                    printf ( "\nno such car!!\n" ) ;
                else
                {
                    printf ( "\ncar found at lane %d slot %d\n", lane, s ) ;
                    del_dq ( &front[ lane ], &rear[ lane ], s ) ;
                }
            }
            elseif ( ad == 'Q' )
                    exit ( 1 ) ;
        }
    }
}

/* adds a new element at the end of queue */
void add_dq ( struct node **f, struct node **r, int tb, char *p )
{
    struct node *q ;
    /* create new node */

    q = ( struct node * ) malloc ( sizeof ( struct node ) ) ;
    strcpy ( q -> plate, p ) ;
    q -> link = NULL ;

    /* if the queue is empty */
if ( *f == NULL )
        *f = q ;
    else
    {
        if ( tb == BOT )
            ( *r ) -> link = q ;
        else
        {
            q -> link = *f ;
            *f = q ;
            return ;
        }
    }
    *r = q ;
}

char* del_dq ( struct node **f, struct node **r, int n )
{
    struct node *q, *top = NULL ;
    /* if queue is empty */
if ( *f == NULL )
        printf ( "queue is empty" ) ;
    else
    {
        if ( n == 0 )
        {
            strcpy ( temp, ( *f ) -> plate ) ;
            q = *f ;
            *f = ( *f ) -> link ;
            free ( q ) ;
            return temp ;
        }

        /* locate node */
for ( i = 0 ; i < n ; i++ )
        {
            /* drive out cars */

            push ( &top, ( *f ) -> plate ) ;

            /* delete the node */

            q = *f ;
            *f = q -> link ;
            free ( q ) ;
        }

        /* delete the nth node */

        q = *f ;
        *f = q -> link ;
        free ( q ) ;

        for ( i = 0 ; i < n ; i++ )
        {
            strcpy ( temp, pop ( &top ) ) ;

            /* add the node */

            add_dq ( f, r, TOP, temp ) ;
        }
    }
}

int count ( struct node *q )
{
    int c = 0 ;

    /* traverse the entire linked list */
while ( q!= NULL )
    {
        q = q -> link ;
        c++ ;
    }
    return c ;
}

int search ( struct node *q, char *p )
{
    int s = -1, c = 0 ;

    while ( q != NULL )
    {
        if ( strcmp ( p, q -> plate ) == 0 )
        {
            s = c ;
            break ;
        }
        else
        {
            q = q -> link ;
            c++ ;
        }
    }
    return ( s ) ;
}

/* adds a new element to the top of stack */
void push ( struct node **s, char* item )
{
    struct node *q ;
    q = ( struct node* ) malloc ( sizeof ( struct node ) ) ;
    strcpy ( q -> plate, item ) ;
    q -> link = *s ;
    *s = q ;
}

/* removes an element from top of stack */
char* pop ( struct node **s )
{
    struct node *q ;

    /* if stack is empty */
if ( *s == NULL )
    {
        return NULL ;
    }
    else
    {
        q = *s ;
        strcpy ( temp, q -> plate ) ;
        *s = q -> link ;
        free ( q ) ;
        return ( temp ) ;
    }
}

void q_display ( struct node *q )
{
    while( q != NULL )
    {
        printf ( "%s", q -> plate ) ;
        q = q -> link ;
    }
    printf ( "\n" ) ;
}

Program to convert an expression in postfix form to an infix form.

Program to convert an expression in postfix form to an infix form.

Code for Program to convert an expression in postfix form to an infix form in C Programming

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

#define MAX 50

struct postfix
{
    char stack[MAX][MAX], target[MAX] ;
    char temp1[2], temp2[2] ;
    char str1[MAX], str2[MAX], str3[MAX] ;
    int i, top ;
} ;

void initpostfix ( struct postfix * ) ;
void setexpr ( struct postfix *, char * ) ;
void push ( struct postfix *, char * ) ;
void pop ( struct postfix *, char * ) ;
void convert ( struct postfix * ) ;
void show ( struct postfix ) ;

void main( )
{
    struct postfix q ;
    char expr[MAX] ;

    clrscr( ) ;

    initpostfix ( &q ) ;

    printf ( "\nEnter an expression in postfix form: " ) ;
    gets ( expr ) ;

    setexpr ( &q, expr ) ;
    convert ( &q ) ;

    printf ( "\nThe infix expression is: " ) ;
    show ( q ) ;

    getch( ) ;
}

/* initializes data member */
void initpostfix ( struct postfix *p )
{
    p -> i = 0 ;
    p -> top = -1 ;
    strcpy ( p -> target, "" ) ;
}

/* copies given expression to target string */
void setexpr ( struct postfix *p, char *c )
{
    strcpy ( p -> target, c ) ;
}

/* adds an expr. to the stack */
void push ( struct postfix *p, char *str )
{
    if ( p -> top == MAX - 1 )
        printf ( "\nStack is full." ) ;
    else
    {
        p -> top++ ;
        strcpy ( p -> stack[p -> top], str ) ;
    }
}

/* pops an expr. from the stack */
void pop ( struct postfix *p, char *a )
{
    if ( p -> top == -1 )
        printf ( "\nStack  is empty." ) ;
    else
    {
        strcpy ( a, p -> stack[p -> top] ) ;
        p -> top-- ;
    }
}

/* converts given expr. to infix form */
void convert ( struct postfix *p )
{
    while ( p -> target[p -> i] )
    {
        /* skip whitespace, if any */
if( p -> target[p -> i] == ' ' )
            p -> i++ ;
        if ( p -> target[p -> i] == '%' || p -> target[p -> i] == '*' ||
             p -> target[p -> i] == '-' || p -> target[p -> i] == '+' ||
             p -> target[p -> i] == '/' || p -> target[p -> i] == '$' )
        {
            pop ( p, p -> str2 ) ;
            pop ( p, p -> str3 ) ;
            p -> temp1[0] = p -> target[p -> i] ;
            p -> temp1[1] = '\0' ;
            strcpy ( p -> str1, p -> str3 ) ;
            strcat ( p -> str1, p -> temp1 ) ;
            strcat ( p -> str1, p -> str2 ) ;
            push ( p, p -> str1 ) ;
        }
        else
        {
            p -> temp1[0] = p -> target[p -> i] ;
            p -> temp1[1] = '\0' ;
            strcpy ( p -> temp2, p -> temp1 ) ;
            push ( p, p -> temp2 ) ;
        }
        p -> i++ ;
    }
}

/* displays the expression */
void show ( struct postfix p )
{
    char *t ;
    t = p.stack[0] ;
    while ( *t )
    {
        printf ( "%c ", *t ) ;
        t++ ;
    }
}

Program to reconstruct a binary search tree.

Program to reconstruct a binary search tree.

Code for Program to reconstruct a binary search tree in C Programming


#include <stdio.h>
#include <conio.h>
#include <alloc.h>

#define MAX 101

struct node
{
    struct node *left ;
    int data ;
    struct node *right ;
} ;

void insert ( struct node **, int ) ;
void preorder ( struct node * ) ;
void postorder ( struct node * ) ;
void inorder ( struct node * ) ;
struct node * recons ( int *, int *, int ) ;
void deltree ( struct node * ) ;

intin[MAX], pre[MAX], x ;

void main( )
{
    struct node *t, *p, *q ;
    int req, i, num ;

    t = NULL ;  /* empty tree */


    clrscr( ) ;
    printf ( "Specify the number of items to be inserted: " ) ;
    while ( 1 )
    {
        scanf ( "%d", &req ) ;
        if ( req >= MAX || req <= 0 )
            printf ( "\nEnter number between 1 to 100.\n" ) ;
        elsebreak ;
    }

    for ( i = 0 ; i < req ; i++ )
    {
        printf ( "Enter the data: " ) ;
        scanf ( "%d", &num ) ;
        insert ( &t, num ) ;
    }

    printf ( "\nIn-order   Traversal:\n" ) ;
    x = 0 ;
    inorder ( t ) ;

    printf ( "\nPre-order  Traversal:\n" ) ;
    x = 0 ;
    preorder ( t ) ;

    printf ( "\nPost-order Traversal:\n" ) ;
    x = 0 ;
    postorder ( t ) ;

    deltree ( t ) ;
    t = NULL ;
    t = recons ( in, pre, req ) ;

    printf ( "\n\nAfter reconstruction of the binary tree.\n" ) ;

    x = 0 ;
    printf ( "\nIn-order   Traversal:\n" ) ;
    inorder ( t ) ;

    x = 0 ;
    printf ( "\nPre-order  Traversal:\n" ) ;
    preorder ( t ) ;
    x = 0 ;
    printf ( "\nPost-order Traversal:\n" ) ;
    postorder ( t ) ;

    deltree ( t ) ;
    getch( ) ;
}

/* inserts a new node in a binary search tree */
void insert ( struct node **sr, int num )
{
    if ( *sr == NULL )
    {
        *sr = ( struct node * ) malloc ( sizeof ( struct node ) ) ;

        ( *sr ) -> left = NULL ;
        ( *sr ) -> data = num ;
        ( *sr ) -> right = NULL ;
        return ;
    }
    else/* search the node to which new node will be attached */

    {
        /* if new data is less, traverse to left */
if ( num < ( *sr ) -> data )
            insert ( &( ( *sr ) -> left ), num ) ;
        else/* else traverse to right */

            insert ( &( ( *sr ) -> right ), num ) ;
    }
}

void preorder ( struct node *t )
{
    if ( t != NULL )
    {
        printf ( "%d\t", pre[x++]= t -> data ) ;
        preorder ( t -> left ) ;
        preorder ( t -> right ) ;
    }
}

void postorder ( struct node *t )
{
    if ( t != NULL )
    {
        postorder ( t -> left ) ;
        postorder ( t -> right ) ;
        printf ( "%d\t", t -> data ) ;
    }
}

void inorder ( struct node *t )
{
    if ( t != NULL )
    {
        inorder ( t -> left ) ;
        printf ( "%d\t", in[x++]= t -> data ) ;
        inorder ( t -> right ) ;
    }
}

struct node * recons ( int *inorder, int *preorder, int noofnodes )
{
    struct node *temp, *left, *right ;
    int tempin[100], temppre[100], i, j ;

    if ( noofnodes == 0 )
        return NULL ;

    temp = ( struct node * ) malloc ( sizeof ( struct node ) ) ;
    temp -> data = preorder[0] ;
    temp -> left = NULL ;
    temp -> right = NULL ;

    if ( noofnodes == 1 )
        return temp ;
    for ( i = 0 ; inorder[i] != preorder[0] ; )
        i++ ;

    if ( i > 0 )
    {
        for ( j = 0 ; j <= i  ; j++ )
            tempin[j] = inorder[j] ;

        for ( j = 0 ; j < i  ; j++ )
            temppre[j] = preorder[j + 1] ;
    }

    left = recons ( tempin, temppre, i ) ;
    temp -> left = left ;

    if ( i < noofnodes - 1 )
    {
        for ( j = i ; j < noofnodes - 1 ; j++ )
        {
            tempin[j - i] = inorder[j + 1] ;
            temppre[j - i] = preorder[j + 1] ;
        }
    }

    right = recons ( tempin, temppre, noofnodes - i - 1 ) ;
    temp -> right = right ;

    return temp ;
}

void deltree ( struct node *t )
{
    if ( t != NULL )
    {
        deltree ( t -> left ) ;
        deltree ( t -> right ) ;
    }
    free ( t ) ;
}

Write a program to add record in a file, search record by name telephone number and display all records from a file.

Code for Program to add record in a file, search record by name telephone number and display all records from a file in C Programming

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

struct teledir{
        long teleno ;
        char name[20];
        char address[20];
};

main()
{
    struct teledir t;
    FILE *fp;
    long tno;
    char sname[20],c;
    int ch;
    while(1)
    {
        clrscr();
        printf("\t\t\t\tMENU\n");
        printf("1. TO ADD THE RECORD IN THE FILE.\n");
        printf("2. TO SEARCH THE RECORD BY NAME.\n");
        printf("3. TO SERACH THE RECORD BY TELEPHONE NUMBER.\n");
        printf("4. TO SEE ALL THE RECORD.");
        printf("5. TO EXIT.\n");
        printf("ENTER YOUR CHOICE:->");
        scanf("%d",&ch);
        switch(ch)
        {
            case 1:
                    fp=fopen("telephon.txt","ab");
                    while (1)
                    {
                      clrscr();
                      printf("ENTER THE TELEPHONE NUMBER:->");
                      scanf("%ld",&t.teleno);
                      fflush(stdin);
                      printf("\nENTER THE NAME               :->");
                      scanf("%s",t.name);
                      fflush(stdin);
                      printf("\nENTER THE ADDRESS            :->");
                      scanf("%s",t.address);
                      fwrite(&t,sizeof(t),1,fp);
                      fflush(stdin);
                      printf("\n\nWISH TO CONTINUE?(Y/N)");
                      scanf("%c",&c);
                      if(c=='n' || c=='N')
                            break;
                    }
                    fclose(fp);
                    break;
            case 2:
                    fp=fopen("telephon.txt","rb");
                    clrscr();
                    printf("ENTER THE NAME    :->");
                    scanf("%s",sname);
                    while(fread(&t,sizeof(t),1,fp))
                    {
                        if(strcmp(sname,t.name)==0)
                        {
                            printf("\n\t%ld\t %s\t %s",t.teleno,t.name,t.address);
                            getch();
                            break;
                        }
                    }
                    fclose(fp);
                    getch();
                    break;
            case 4:
                    exit(1);
        }
    }
        getch();

}

Example of passing structure to function.

Example of passing structure to function.

Code for Example of passing structure to function in C Programming

struct student
     {
    name char[30];
    marks float;
     }
main ( )
{
    struct student student1;
    student1 = read_student ( )
    print_student( student1);
    read_student_p(student1);
    print_student (student1);
 }
struct student read_student( )    \\ A
{
    struct student student2;
    gets(student2.name);
    scanf(“%d”,&student2.marks);
    return (student2);
}
  void print_student (struct student student2)    \\ B
{
printf( “name is %s\n”, student2.name);
printf( “marks are%d\n”, student2.marks);
}
  void read_student_p(struct student student2)    \\ C
{
    gets(student2.name);
    scanf(“%d”,&student2.marks);

}

Program to maintain a threaded binary tree.

Program to maintain a threaded binary tree.

Code for Program to maintain a threaded binary tree in C Programming

#include <stdio.h>
#include <conio.h>
#include <alloc.h>

enum boolean
{
    false = 0,
    true = 1
} ;

struct thtree
{
    enum boolean isleft ;
    struct thtree *left ;
    int data ;
    struct thtree *right ;
    enum boolen isright ;
} ;

void insert ( struct thtree **, int ) ;
void delete ( struct thtree **, int ) ;
void search ( struct thtree **, int, struct thtree **,
                struct thtree **, int * ) ;
void inorder ( struct thtree * ) ;
void deltree ( struct thtree ** ) ;

void main( )
{
    struct thtree *th_head ;

    th_head = NULL ;  /* empty tree */


    insert ( &th_head, 11 ) ;
    insert ( &th_head, 9 ) ;
    insert ( &th_head, 13 ) ;
    insert ( &th_head, 8 ) ;
    insert ( &th_head, 10 ) ;
    insert ( &th_head, 12 ) ;
    insert ( &th_head, 14 ) ;
    insert ( &th_head, 15 ) ;
    insert ( &th_head, 7 ) ;

    clrscr( ) ;
    printf ( "Threaded binary tree before deletion:\n" ) ;
    inorder ( th_head ) ;

    delete ( &th_head, 10 ) ;
    printf ( "\nThreaded binary tree after deletion:\n" ) ;
    inorder ( th_head ) ;

    delete ( &th_head, 14 ) ;
    printf ( "\nThreaded binary tree after deletion:\n" ) ;
    inorder ( th_head ) ;

    delete ( &th_head, 8 ) ;
    printf ( "\nThreaded binary tree after deletion:\n" ) ;
    inorder ( th_head ) ;

    delete ( &th_head, 13 ) ;
    printf ( "\nThreaded binary tree after deletion:\n" ) ;
    inorder ( th_head ) ;

    deltree ( &th_head ) ;

    getch( ) ;
}

/* inserts a node in a threaded binary tree */
void insert ( struct thtree **s, int num )
{
    struct thtree *p, *z, *head = *s ;

    /* allocating a new node */

    z = malloc ( sizeof ( struct thtree ) ) ;

    z -> isleft = true ;  /* indicates a thread */

    z -> data = num ;  /* assign new data */

    z -> isright = true ;  /* indicates a thread */
/* if tree is empty */
if ( *s == NULL )
    {
        head = malloc ( sizeof ( struct thtree ) ) ;

        /* the entire tree is treated as a left sub-tree of the head node */

        head -> isleft = false ;
        head -> left = z ;  /* z becomes leftchild of the head node */

        head -> data = -9999 ;  /* no data */

        head -> right = head ;  /* right link will always be pointing
                                    to itself */

        head -> isright = false ;

        *s = head ;

        z -> left = head ;  /* left thread to head */

        z -> right = head ;  /* right thread to head */

    }
    else/* if tree is non-empty */

    {
        p = head -> left ;

        /* traverse till the thread is found attached to the head */
while ( p != head )
        {
            if ( p -> data > num )
            {
                if ( p -> isleft != true )  /* checking for a thread */

                    p = p -> left ;
                else
                {
                    z -> left = p -> left ;
                    p -> left = z ;
                    p -> isleft = false ;  /* indicates a link */

                    z -> isright = true ;
                    z -> right = p ;
                    return ;
                }
            }
            else
            {
                if ( p -> data < num )
                {
                    if ( p -> isright != true )
                        p = p -> right ;
                    else
                    {
                        z -> right = p -> right ;
                        p -> right = z ;
                        p -> isright = false ;  /* indicates a link */

                        z -> isleft = true ;
                        z -> left = p ;
                        return ;
                    }
                }
            }
        }
    }
}

/* deletes a node from the binary search tree */
void delete ( struct thtree **root, int num )
{
    int found ;
    struct thtree *parent, *x, *xsucc ;

    /* if tree is empty */
if ( *root == NULL )
    {
        printf ( "\nTree is empty" ) ;
        return ;
    }

    parent = x = NULL ;

    /* call to search function to find the node to be deleted */

    search ( root, num, &parent, &x, &found ) ;

    /* if the node to deleted is not found */
if ( found == false )
    {
        printf ( "\nData to be deleted, not found" ) ;
        return ;
    }

    /* if the node to be deleted has two children */
if ( x -> isleft == false && x -> isright == false )
    {
        parent = x ;
        xsucc = x -> right ;

        while ( xsucc -> isleft == false )
        {
            parent = xsucc ;
            xsucc = xsucc -> left ;
        }

        x -> data = xsucc -> data ;
        x = xsucc ;
    }

    /* if the node to be deleted has no child */
if ( x -> isleft == true && x -> isright == true )
    {
        /* if node to be deleted is a root node */
if ( parent == NULL )
        {
            ( *root ) -> left = *root ;
            ( *root ) -> isleft = true ;

            free ( x ) ;
            return ;
        }

        if ( parent -> right == x )
        {
            parent -> isright = true ;
            parent -> right = x -> right ;
        }
        else
        {
            parent -> isleft = true ;
            parent -> left = x -> left ;
        }

        free ( x ) ;
        return ;
    }

    /* if the node to be deleted has only rightchild */
if ( x -> isleft == true && x -> isright == false )
    {
        /* node to be deleted is a root node */
if ( parent == NULL )
        {
            ( *root ) -> left = x -> right ;
            free ( x ) ;
            return ;
        }

        if ( parent -> left == x )
        {
            parent -> left = x -> right ;
            x -> right -> left = x -> left ;
        }
        else
        {
            parent -> right = x -> right ;
            x -> right -> left = parent ;
        }

        free ( x ) ;
        return ;
    }

    /* if the node to be deleted has only left child */
if ( x -> isleft == false && x -> isright == true )
    {
        /* the node to be deleted is a root node */
if ( parent == NULL )
        {
            parent = x ;
            xsucc = x -> left ;

            while ( xsucc -> right == false )
            xsucc = xsucc -> right ;

            xsucc -> right = *root ;

            ( *root ) -> left = x -> left ;

            free ( x ) ;
            return ;
        }

        if ( parent -> left == x )
        {
            parent -> left = x -> left ;
            x -> left -> right = parent ;
        }
        else
        {
            parent -> right = x -> left ;
            x -> left -> right = x -> right ;
        }

        free ( x ) ;
        return ;
    }
}

/* returns the address of the node to be deleted, address of its parent and
    whether the node is found or not */
void search ( struct thtree **root, int num, struct thtree **par,
                struct thtree **x, int *found )
{
    struct thtree *q ;

    q = ( *root ) -> left ;
    *found = false ;
    *par = NULL ;

    while ( q != *root )
    {
        /* if the node to be deleted is found */
if ( q -> data == num )
        {
            *found = true ;
            *x = q ;
            return ;
        }

        *par = q ;

        if ( q -> data > num )
        {
            if ( q -> isleft == true )
            {
                *found = false ;
                x = NULL ;
                return ;
            }
            q = q -> left ;
        }
        else
        {
            if ( q -> isright == true )
            {
                *found = false ;
                *x = NULL ;
                return ;
            }
            q = q -> right ;
        }
    }
}

/* traverses the threaded binary tree in inorder */
void inorder ( struct thtree *root )
{
    struct thtree *p ;

    p = root -> left ;

    while ( p != root )
    {
        while ( p -> isleft == false )
            p = p -> left ;

        printf ( "%d\t", p -> data ) ;

        while ( p -> isright == true )
        {
            p = p -> right ;

            if ( p == root )
                break ;

            printf ( "%d\t", p -> data ) ;

        }
        p = p -> right ;
    }
}

void deltree ( struct thtree **root )
{
    while ( ( *root ) -> left != *root )
        delete ( root, ( *root ) -> left -> data ) ;
}

Program to insert and delete a node from the binary search tree.

Program to insert and delete a node from the binary search tree.

Code for Program to insert and delete a node from the binary search tree in C Programming

#include <stdio.h>
#include <conio.h>
#include <alloc.h>

#define TRUE 1
#define FALSE 0

struct btreenode
{
    struct btreenode *leftchild ;
    int data ;
    struct btreenode *rightchild ;
} ;

void insert ( struct btreenode **, int ) ;
void delete ( struct btreenode **, int ) ;
void search ( struct btreenode **, int, struct btreenode **,
                struct btreenode **, int * ) ;
void inorder ( struct btreenode * ) ;

void main( )
{
    struct btreenode *bt ;
    int req, i = 0, num, a[ ] = { 11, 9, 13, 8, 10, 12, 14, 15, 7 } ;

    bt = NULL ;  /* empty tree */


    clrscr( ) ;

    while ( i <= 8 )
    {
        insert ( &bt, a[i] ) ;
        i++ ;
    }
    clrscr( ) ;
    printf ( "Binary tree before deletion:\n" ) ;
    inorder ( bt ) ;

    delete ( &bt, 10 ) ;
    printf ( "\nBinary tree after deletion:\n" ) ;
    inorder ( bt ) ;

    delete ( &bt, 14 ) ;
    printf ( "\nBinary tree after deletion:\n" ) ;
    inorder ( bt ) ;

    delete ( &bt, 8 ) ;
    printf ( "\nBinary tree after deletion:\n" ) ;
    inorder ( bt ) ;

    delete ( &bt, 13 ) ;
    printf ( "\nBinary tree after deletion:\n" ) ;
    inorder ( bt ) ;
}

/* inserts a new node in a binary search tree */
void insert ( struct btreenode **sr, int num )
{
    if ( *sr == NULL )
    {
        *sr = malloc ( sizeof ( struct btreenode ) ) ;

        ( *sr ) -> leftchild = NULL ;
        ( *sr ) -> data = num ;
        ( *sr ) -> rightchild = NULL ;
    }
    else/* search the node to which new node will be attached */

    {
        /* if new data is less, traverse to left */
if ( num < ( *sr ) -> data )
            insert ( &( ( *sr ) -> leftchild ), num ) ;
        else/* else traverse to right */

            insert ( &( ( *sr ) -> rightchild ), num ) ;
    }
}

/* deletes a node from the binary search tree */
void delete ( struct btreenode **root, int num )
{
    int found ;
    struct btreenode *parent, *x, *xsucc ;

    /* if tree is empty */
if ( *root == NULL )
    {
        printf ( "\nTree is empty" ) ;
        return ;
    }

    parent = x = NULL ;

    /* call to search function to find the node to be deleted */

    search ( root, num, &parent, &x, &found ) ;

    /* if the node to deleted is not found */
if ( found == FALSE )
    {
        printf ( "\nData to be deleted, not found" ) ;
        return ;
    }

    /* if the node to be deleted has two children */
if ( x -> leftchild != NULL && x -> rightchild != NULL )
    {
        parent = x ;
        xsucc = x -> rightchild ;

        while ( xsucc -> leftchild != NULL )
        {
            parent = xsucc ;
            xsucc = xsucc -> leftchild ;
        }

        x -> data = xsucc -> data ;
        x = xsucc ;
    }

    /* if the node to be deleted has no child */
if ( x -> leftchild == NULL && x -> rightchild == NULL )
    {
        if ( parent -> rightchild == x )
            parent -> rightchild = NULL ;
        else
            parent -> leftchild = NULL ;

        free ( x ) ;
        return ;
    }

    /* if the node to be deleted has only rightchild */
if ( x -> leftchild == NULL && x -> rightchild != NULL )
    {
        if ( parent -> leftchild == x )
            parent -> leftchild = x -> rightchild ;
        else
            parent -> rightchild = x -> rightchild ;

        free ( x ) ;
        return ;
    }

    /* if the node to be deleted has only left child */
if ( x -> leftchild != NULL && x -> rightchild == NULL )
    {
        if ( parent -> leftchild == x )
            parent -> leftchild = x -> leftchild ;
        else
            parent -> rightchild = x -> leftchild ;

        free ( x ) ;
        return ;
    }
}

/*returns the address of the node to be deleted, address of its parent and
   whether the node is found or not */
void search ( struct btreenode **root, int num, struct btreenode **par, struct
        btreenode **x, int *found )
{
    struct btreenode *q ;

    q = *root ;
    *found = FALSE ;
    *par = NULL ;

    while ( q != NULL )
    {
        /* if the node to be deleted is found */
if ( q -> data == num )
        {
            *found = TRUE ;
            *x = q ;
            return ;
        }

        *par = q ;

        if ( q -> data > num )
            q = q -> leftchild ;
        else
            q = q -> rightchild ;
    }
}

/* traverse a binary search tree in a LDR (Left-Data-Right) fashion */
void inorder ( struct btreenode *sr )
{
    if ( sr != NULL )
    {
        inorder ( sr -> leftchild ) ;

        /* print the data of the node whose leftchild is NULL or the path  has
            already been traversed */

        printf ( "%d\t", sr -> data ) ;

        inorder ( sr -> rightchild ) ;
    }
}

Program to maintain a heap.

Program to maintain a heap.

Code for Program to maintain a heap in C Programming


#include <stdio.h>
#include <conio.h>

void restoreup ( int, int * ) ;
void restoredown ( int, int *, int ) ;
void makeheap ( int *, int ) ;
void add ( int, int *, int * ) ;
int replace ( int, int *, int ) ;
int del ( int *, int * ) ;

void main( )
{
    int arr [20] = { 1000, 7, 10, 25, 17, 23, 27, 16,
                    19, 37, 42, 4, 33, 1, 5, 11 } ;
    int i, n = 15 ;

    clrscr( ) ;
    makeheap ( arr, n ) ;

    printf ( "Heap:\n" ) ;
    for ( i = 1 ; i <= n ; i++ )
        printf ( "%d\t", arr [i] ) ;

    i = 24 ;
    add ( i, arr, &n ) ;

    printf ( "\n\nElement added %d.\n", i ) ;
    printf ( "\nHeap after addition of an element:\n" ) ;
    for ( i = 1 ; i <= n ; i++ )
        printf ( "%d\t", arr [i] ) ;

    i = replace ( 2, arr, n ) ;
    printf ( "\n\nElement replaced %d.\n", i ) ;
    printf ( "\nHeap after replacement of an element:\n" ) ;
    for ( i = 1 ; i <= n ; i++ )
        printf ( "%d\t", arr [i] ) ;

    i = del ( arr, &n ) ;
    printf ( "\n\nElement deleted %d.\n", i ) ;
    printf ( "\nHeap after deletion of an element:\n" ) ;
    for ( i = 1 ; i <= n ; i++ )
        printf ( "%d\t", arr [i] ) ;

    getch( ) ;
}

void restoreup ( int i, int *arr )
{
    int val ;
    val = arr [i] ;
    while ( arr [i / 2] <= val )
    {
        arr [i] = arr [i / 2] ;
        i = i / 2 ;
    }
    arr [i] = val ;
}

void restoredown ( int pos, int *arr, int n )
{
    int i, val ;
    val = arr [pos] ;
    while ( pos <= n / 2 )
    {
        i = 2 * pos ;
        if ( ( i < n ) && ( arr [i] < arr [i + 1] ) )
            i++ ;
        if ( val >= arr [i] )
            break ;
        arr [pos] = arr [i] ;
        pos = i ;
    }
    arr [pos] = val ;
}

void makeheap ( int *arr, int n )
{
    int i ;
    for ( i = n / 2 ; i >= 1 ; i-- )
        restoredown ( i, arr, n ) ;
}

void add ( int val, int *arr, int *n )
{
    ( *n ) ++ ;
    arr [*n] = val ;
    restoreup ( *n, arr ) ;
}
int replace ( int i, int *arr, int n )
{
    int r = arr [1] ;
    arr [1] = i ;
    for ( i = n / 2 ; i >= 1 ; i-- )
        restoredown ( i, arr, n ) ;
    return r ;
}

int del ( int *arr, int *n )
{
    int val ;
    val = arr [1] ;
    arr [1] = arr [*n] ;
    ( *n ) -- ;
    restoredown ( 1, arr, *n ) ;
    return val ;
}

Write a program to calculate x raise to y or power(x,y) using while loop.

Code for Program to calculate x raise to y or power(x,y) using while loop in C Programming

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

void main()
{
    int x,y;
    double power();
    clrscr();

    printf("Enter value of x : ");
    scanf("%d",&x);
    printf("Enter value of y : ");
    scanf("%d",&y);

    printf("%d to power %d is = %f\n",x,y,power(x,y));
    getch();
}
double power(x,y)
int x,y;
{
    double p;
    p=1.0;
    if(y>=0)
        while(y--)
            p*=x;
    elsewhile(y++)
            p/=x;
    return(p);
}

WRITE A PROGRAM TO READ AGE OF N PERSONS AND DISPLAY ONLY THOSE PERSONS WHOSE BETWEEN 50 AND 60.

Code for PROGRAM TO READ AGE OF N PERSONS AND DISPLAY ONLY THOSE PERSONS WHOSE BETWEEN 50 AND 60 in C Programming

#include<stdio.h>
#include<conio.h>

void main()
{
    int i,n,age[100],count=0;

    clrscr();

    printf("Enter the number of persons  ::  ");
    scanf("%d",&n);

    for (i=1;i<=n;i++)
    {
        printf("\nEnter age of %d persons :: ",i);
        scanf("%d",&age[i]);
    }

    for (i=1;i<=n;i++)
    {
        if(age[i]>50 && age[i] < 60)
        count++;
        elsecontinue;
    }

    printf("\n\nNumber of persons whose age between 50-60 are :: %d",count);
    getch();
}


/*
    **********
    OUTPUT
    **********

    Enter the number of persons  ::  6

    Enter age of 1 persons :: 10

    Enter age of 2 persons :: 20

    Enter age of 3 persons :: 30

    Enter age of 4 persons :: 55

    Enter age of 5 persons :: 51

    Enter age of 6 persons :: 56


    Number of persons whose age between 50-60 are :: 3

Write a program to interchange the Small and Capital Letters.




Code for Program to interchange the Small and Capital Letters in C Programming

 # include <dos.h>


 void interrupt (*OldInterruptFunction)( );
 void interrupt NewInterruptFunction( );


 int main( )
 {
    OldInterruptFunction=getvect(0x17);
    setvect(0x17,NewInterruptFunction);

    keep(0,(_SS+(_SP/16)-_psp));

    return 0;
 }

 /*************************************************************************///---------------------  NewInterruptFunction( )  -----------------------///*************************************************************************/void interrupt NewInterruptFunction( )
 {
    if(_AH==0x00)
    {
       if(_AL>='a' && _AL<='z')
      _AL-=32;

       elseif(_AL>='A' && _AL<='Z')
      _AL+=32;
    }

    (*OldInterruptFunction)( );
 }

write a program that takes a number from user and calculates its logarithm value to the base 10 and e, exponentiation, sin value, cosine value and square root.

write a program that takes a number from user and
calculates its logarithm value to the base 10 and
e, exponentiation, sin value, cosine value and
square root.

Code for program that takes a number from user and calculates its logarithm value to the base 10 and e, exponentiation, sin value, cosine value and square root in C Programming

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
        float n,log,ex,sinv,cosv,sq;
        clrscr();
        printf("\n\n PLEASE ENTER THE VALUE OF N: ");
        scanf("%f",&n);
        log=log10(n);
        ex=exp(n);
        sinv=sin(n);
        cosv=cos(n);
        sq=sqrt(n);
        printf("\n\n THE VALUE OF N IS %.4f .",n);
        printf("\n\n THE VALUE OF LOGARITHAM BASE 10 IS %.4f .",log);
        printf("\n\n THE VALUE OF EXPONENTIATION IS %.4f .",ex);
        printf("\n\n THE VALUE OF SIN VALUE IS %.4f .",sinv);
        printf("\n\n THE VALUE OF COSINE VALUE IS %.4f .",cosv);
        printf("\n\n THE VALUE OF SQURE ROOT IS %.4f .",sq);
    getch();
}


*********************** OUTPUT*************************************************

     PLEASE ENTER THE VALUE OF N: 5


     THE VALUE OF N IS 5.0000 .

     THE VALUE OF LOGARITHAM BASE 10 IS 0.6990 .

     THE VALUE OF EXPONENTIATION IS 148.4132 .

     THE VALUE OF SIN VALUE IS -0.9589 .

     THE VALUE OF COSINE VALUE IS 0.2837 .

     THE VALUE OF SQURE ROOT IS 2.2361 .

calculate average of the elements of an array and then the average deviation using barrier.

Write a program to calculate average of the elements of an array and then the average deviation using barrier.



Code for Program to calculate average of the elements of an array and then the average deviation using barrier in C Programming

# include <stdio.h>
# include <math.h>
# include "/usr/include/sys/types.h"
# include "/usr/include/sys/shm.h"
# include "/usr/include/sys/ipc.h"
# include "/usr/include/sys/sem.h"
# include "forkjoin.h"
# include "sharedlib.h"
# include "spinlock.h"
# include "barrier.h"int main()
{
    int arr[100];
    int *bararr;        // Barrier Arrayint arrSize;        //Size of arrayint iCount;        //Counter Variableint id;            //Process IDint nProc=3;        //number of Processesfloat sum=0;
    
    float *deviation,*avg;  // Shared Variablesint *lock;        // Shared Variable for Spinlockint shmidavg,shmidlock,shmiddeviation,shmidbararr;    // Shmid for Shared Variables
    
    printf("Enter the Size of an Array :");
    scanf("%d",&arrSize);

    for(iCount=0;iCount<arrSize;iCount++)
    {
        printf("Enter arr[%d] :",iCount);
        scanf("%d",&arr[iCount]);
    }

    /* Allocate Shared memory */
    avg=(float*)sshared(sizeof(float),&shmidavg);
    deviation=(float*)sshared(sizeof(float),&shmiddeviation);
    lock=(int*)sshared(sizeof(int),&shmidlock);
    bararr=(int*)sshared(sizeof(int)*4,&shmidbararr);

    spin_lock_init(lock);        // Spin Lock Initialization
    
    barrier_init(bararr,nProc);    // Barrier Initialization
    
    *avg=0;

    id=process_fork(nProc);        // Forking Processes/* Partial Sum using Loop Spliting */for(iCount=id;iCount<arrSize;iCount=iCount+nProc)
    {
        sum = sum + arr[iCount];
    }

    spin_lock(lock);
        /* Critical Region */
        *avg = *avg + ( sum /arrSize);    // Calculate Average from Partial Sums
    spin_unlock(lock);

    /*    ---------------------------------------------------------------------------    Barrier Should be here, So that all Processes have to wait until Final    Average is Calculated.    ---------------------------------------------------------------------------    */
    
    barrier(bararr);    // Barrier Called
    
    
    sum=0;
    /* Calculate Sum(Xi - Mean) Using Loop Spliting */for(iCount=id;iCount<arrSize;iCount=iCount+nProc)
    {
        sum = sum + pow(((float)arr[iCount] - *avg),2);
    }
    
    spin_lock(lock);
        /* Critical Region */
        *deviation = *deviation + (sum / arrSize-1); // Calculate Final Deviation
    spin_unlock(lock);

    
    process_join(nProc,id);        // Joining the Process

    *deviation=sqrt(*deviation);
    printf("Deviation : %f\n",*deviation);

    /* Cleaning the Shared Region */
    cleanup_memory(&shmidavg);
    cleanup_memory(&shmidlock);
    cleanup_memory(&shmiddeviation);
    cleanup_memory(&shmidbararr);
    return 0;
}

Program to add two polynomials.

Program to add two polynomials.

Code for Program to add two polynomials in C Programming

#include <stdio.h>
#include <conio.h>

#define MAX 10

struct term
{
    int coeff ;
    int exp ;
} ;

struct poly
{
    struct term t [10] ;
    int noofterms ;
} ;


void initpoly ( struct poly * ) ;
void polyappend ( struct poly *, int c, int e ) ;
struct poly polyadd ( struct poly, struct poly ) ;
void display ( struct poly ) ;

void main( )
{
    struct poly p1, p2, p3 ;

    clrscr( ) ;

    initpoly ( &p1 ) ;
    initpoly ( &p2 ) ;
    initpoly ( &p3 ) ;

    polyappend ( &p1, 1, 7 ) ;
    polyappend ( &p1, 2, 6 ) ;
    polyappend ( &p1, 3, 5 ) ;
    polyappend ( &p1, 4, 4 ) ;
    polyappend ( &p1, 5, 2 ) ;

    polyappend ( &p2, 1, 4 ) ;
    polyappend ( &p2, 1, 3 ) ;
    polyappend ( &p2, 1, 2 ) ;
    polyappend ( &p2, 1, 1 ) ;
    polyappend ( &p2, 2, 0 ) ;

    p3 = polyadd ( p1, p2 ) ;

    printf ( "\nFirst polynomial:\n" ) ;
    display ( p1 ) ;

    printf ( "\n\nSecond polynomial:\n" ) ;
    display ( p2 ) ;

    printf ( "\n\nResultant polynomial:\n" ) ;
    display ( p3 ) ;

    getch( ) ;
}

/* initializes elements of struct poly */
void initpoly ( struct poly *p )
{
    int i ;
    p -> noofterms = 0 ;
    for ( i = 0 ; i < MAX ; i++ )
    {
        p -> t[i].coeff = 0 ;
        p -> t[i].exp = 0 ;
    }
}

/* adds the term of polynomial to the array t */
void polyappend ( struct poly *p, int c, int e )
{
    p -> t[p -> noofterms].coeff = c ;
    p -> t[p -> noofterms].exp =  e ;
    ( p -> noofterms ) ++ ;
}

/* displays the polynomial equation */
void display ( struct poly p )
{
    int flag = 0, i ;
    for ( i = 0 ; i < p.noofterms ; i++ )
    {
        if ( p.t[i].exp != 0 )
            printf ( "%d x^%d + ", p.t[i].coeff, p.t[i].exp ) ;
        else
        {
            printf ( "%d", p.t[i].coeff ) ;
            flag = 1 ;
        }
    }
    if ( !flag )
        printf ( "\b\b  " ) ;

}

/* adds two polynomials p1 and p2 */
struct poly polyadd ( struct poly p1, struct poly p2 )
{
    int i, j, c ;
    struct poly p3 ;
    initpoly ( &p3 ) ;

    if ( p1.noofterms > p2.noofterms )
        c = p1.noofterms ;
    else
        c = p2.noofterms ;

    for ( i = 0, j = 0 ; i <= c ; p3.noofterms++ )
    {
        if ( p1.t[i].coeff == 0 && p2.t[j].coeff == 0 )
            break ;
        if ( p1.t[i].exp >= p2.t[j].exp )
        {
            if ( p1.t[i].exp == p2.t[j].exp )
            {
                p3.t[p3.noofterms].coeff = p1.t[i].coeff + p2.t[j].coeff ;
                p3.t[p3.noofterms].exp = p1.t[i].exp ;
                i++ ;
                j++ ;
            }
            else
            {
                p3.t[p3.noofterms].coeff = p1.t[i].coeff ;
                p3.t[p3.noofterms].exp = p1.t[i].exp ;
                i++ ;
            }
        }
        else
        {
            p3.t[p3.noofterms].coeff = p2.t[j].coeff ;
            p3.t[p3.noofterms].exp = p2.t[j].exp ;
            j++ ;
        }
    }
    return p3 ;
}

Program to build a binary search tree from an array.

Program to build a binary search tree from an array.

Code for Program to build a binary search tree from an array in C Programming

#include <stdio.h>
#include <conio.h>
#include <alloc.h>

struct node
{
    struct node *left ;
    char data ;
    struct node *right ;
} ;

struct node * buildtree ( int ) ;
void inorder ( struct node * ) ;

char a[ ] = {
            'A', 'B', 'C', 'D', 'E', 'F', 'G', '\0', '\0', 'H', '\0',
            '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0'
            } ;

void main( )
{
    struct node *root ;

    clrscr( ) ;

    root = buildtree ( 0 ) ;
    printf ( "In-order Traversal:\n" ) ;
    inorder ( root ) ;

    getch( ) ;
}
struct node * buildtree ( int n )
{
    struct node *temp = NULL ;
    if ( a[n] != '\0' )
    {
        temp = ( struct node * ) malloc ( sizeof ( struct node ) ) ;
        temp -> left = buildtree ( 2 * n + 1 ) ;
        temp -> data = a[n] ;
        temp -> right = buildtree ( 2 * n + 2 ) ;
    }
    return temp ;
}

void inorder ( struct node *root )
{
    if ( root != NULL )
    {
        inorder ( root -> left ) ;
        printf ( "%c\t", root -> data ) ;
        inorder ( root -> right ) ;
    }
}

Program to sort a linked list by swapping data.

Program to sort a linked list by swapping data.

Code for Program to sort a linked list by swapping data in C Programming

#include <stdio.h>
#include <conio.h>
#include <alloc.h>

/* structure containing a data part and link part */
struct node
{
    int data ;
    struct node *link ;
} *newnode, *start, *visit ;

void getdata( ) ;
void append ( struct node **, int ) ;
void displaylist( ) ;
int count ( struct node * ) ;
void selection_sort ( int ) ;
void bubble_sort ( int ) ;

void main( )
{
    int n ;

    getdata( ) ;

    clrscr( ) ;
    printf ( "Linked List Before Sorting: " ) ;
    displaylist( ) ;

    n = count ( start ) ;

    selection_sort ( n ) ;
    printf ( "\nLinked List After Selection Sorting: " ) ;
    displaylist( ) ;
    getch( ) ;

    getdata( ) ;
    clrscr( ) ;
    printf ( "Linked List Before Sorting: " ) ;
    displaylist( ) ;

    n = count ( start ) ;

    bubble_sort ( n ) ;
    printf ( "\nLinked List After Bubble Sorting: " ) ;
    displaylist( ) ;
    getch( ) ;
}

void getdata( )
{
    int val, n ;
    char ch ;
    struct node *new ;

    clrscr( ) ;

    new = NULL ;
    do
    {
        printf ( "\nEnter a value: " ) ;
        scanf ( "%d", &val ) ;

        append ( &new, val ) ;

        printf ( "\nAny More Nodes (Y/N): " ) ;
        ch = getche( ) ;
    } while ( ch == 'y' || ch == 'Y' ) ;

    start = new ;
}

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

    if ( *q == NULL ) /* if the list is empty, create first node */

    {
        *q = malloc ( sizeof ( struct node ) ) ;
        temp = *q ;
    }
    else
    {
        /* go to last node */
while ( temp -> link != NULL )
            temp = temp -> link ;

        /* add node at the end */

        temp -> link = malloc ( sizeof ( struct node ) ) ;
        temp = temp -> link ;
    }

    /* assign data to the last node */

    temp -> data = num ;
    temp -> link = NULL ;
}

/* displays the contents of the linked list */
void displaylist( )
{
    visit = start ;

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

/* counts the number of nodes present in the linked list */
int count ( struct node * q )
{
    int c = 0 ;

    /* traverse the entire linked list */
while ( q != NULL )
    {
        q = q -> link ;
        c++ ;
    }

    return c ;
}

void selection_sort ( int n )
{
    int i, j, k, temp ;
    struct node *p, *q ;

    p = start ;
    for ( i = 0 ; i < n - 1 ; i++ )
    {
        q = p -> link ;

        for ( j = i + 1 ; j < n ; j++ )
        {
            if ( p -> data > q -> data )
            {
                temp = p -> data ;
                p -> data = q -> data ;
                q -> data = temp ;
            }
            q = q -> link ;
        }
        p = p -> link ;
    }
}

void bubble_sort ( int n )
{
    int i, j, k, temp ;
    struct node *p, *q ;

    k = n ;
    for ( i = 0 ; i < n - 1 ; i++, k-- )
    {
        p = start ;
        q = p -> link ;

        for ( j = 1 ; j < k ; j++ )
        {
            if ( p -> data > q -> data )
            {
                temp = p -> data ;
                p -> data = q -> data ;
                q -> data = temp ;
            }
            p = p -> link ;
            q = q -> link ;
        }
    }
}