You are on page 1of 81

Comp Engg, AVCOE, Sangamner

1 /* PROGRAM TO CREAT AVL TREE. Program uses enumerated data type to indicate lefthigh,right high, or equal. Program by: .*/ # include<stdio.h> # include<conio.h> # include<stdlib.h> # include<string.h> typedef enum balancefactor_tag{lh,eh,rh} balancefactor_type; int *taller; struct node /* declaring structure of each node*/ { char name[10]; balancefactor_type bf; struct node *left , *right; }; struct node *root , *p , *q; /*--------------End of declarations -------------------------------*/ struct node *insert(struct node *root,struct node *p, int *taller); void inorder(struct node * ); struct node *leftrotate(struct node *p); struct node *rightrotate(struct node *p); struct node *leftbalance(struct node *root, int *taller); struct node *rightbalance(struct node *root, int *taller); /*------------------Function prototypes-------------------------*/ void main(void) { char ans; int ch1=1; *taller = 0; /* intialize height and root of the tree*/ root = NULL; while( ch1!=3) { clrscr(); printf("\n\n\t\t ***** MENU ****\n"); printf("\n\t\t 1. ADD ELEMENTS "); printf("\n\t\t 2. INORDER "); printf("\n\t\t 3. Exit "); scanf("%d", &ch1); clrscr(); switch(ch1) { case 1 :do{ p = malloc(sizeof(struct node)); printf("\n\t\tENTER THE NAME OT BE ADDED "); scanf("%s", p->name); p->right = NULL; p->left = NULL; root = insert(root,p,taller);

Comp Engg, AVCOE, Sangamner

2 printf("\n Add one more ? "); ans=getch(); }while(ans=='y' || ans=='Y'); break; case 2: printf("\n\t\tINORDER TRAVERSAL\n\n"); printf("ROOT = %s\n\n",root->name); printf(" TREE : "); inorder(root); getch(); break; } } } /*----------------------End of main--------------------------------*/ void inorder(struct node *root) /* Function for inorder traversal */ { if(root != NULL) { inorder(root->left); printf("\t%s", root->name); inorder(root->right); } } /*----------------End of function inorder-------------------------*/ struct node *insert(struct node *root,struct node *p, int *taller) /* function to add new node in AVL tree in proper position */ { if(!root) { root = p; root->bf = eh; root->left = root->right = NULL; *taller = 1; } else if(strcmp(root->name,p->name) == 0) printf("\n\t\tDUPLICATION ERROR!!"); else if(strcmp(root->name,p->name)>0 ) /* if new node is smaller*/ { /*than the present root */ root->left = insert(root->left, p, taller); if(*taller == 1) { switch(root->bf) /* perform balancing */ { case lh :

Comp Engg, AVCOE, Sangamner

3 root = leftbalance(root, taller); break; case eh : root->bf = lh; break; case rh : root->bf = eh; *taller = 0; break; } } } else if(strcmp(root->name,p->name)<0 ) /* if new node is larger*/ { /*greater than the root*/ root->right = insert(root->right, p, taller); if(*taller == 1) { switch(root->bf) /* adjust the heights */ { case lh : root->bf = eh; *taller = 0; break; case eh : root->bf = rh; break; case rh : root = rightbalance(root, taller); break; } } } return(root); } /*---------------------------End of function insert -----------------*/ struct node *rightrotate(struct node *p) /* function for right rotation */ { struct node *temp; if(p==NULL) /* if tree is empty*/ printf("\n\t\tCANNOT ROTATE AN EMPTY TREE"); else if(p->left == NULL) /* if tree can be rotated right*/ printf("\n\t\tCANNOT ROTATE RIGHT");

Comp Engg, AVCOE, Sangamner

4 else { temp = p->left; /* rotate right */ p->left = temp->right; temp->right = p; } return(temp); } /* THIS FUNCTION ROTATES THE TREE/SUBTREE AT 'p' ONCE TOWARDS LEFT */ struct node *leftrotate(struct node *p) { struct node *temp; if(p==NULL) /* check if tree is empty */ printf("\n\t\tCANNOT ROTATE AN EMPTY TREE"); else if(p->right == NULL) /* check if tree can be rotated left*/ printf("\n\t\tCANNOT ROTATE LEFT"); else { temp = p->right; p->right = temp->left; /* rotate left */ temp->left = p; } return(temp); } /*---------------------end of function rotate right-----------------*/ /* FUNCTION TO BALANCE THE SUBTREE AT 'root' IF BALANCE FACTOR*/ /* AT 'root' IS DOUBLE RIGHT HIGH */ struct node *rightbalance(struct node *root, int *taller) { struct node *rs = root->right, *ls; /* ASSIGN rs TO RIGHT SUBTREE OF root*/ switch(rs->bf) { case rh : root->bf = rs->bf = eh; root = leftrotate(root); *taller = 0; break; case eh : printf("\n\tTREE ALREADY BALLANCED"); break; case lh : ls = rs->left; /* ASSIGN ls TO LEFT SUBTREE OF rs */

Comp Engg, AVCOE, Sangamner

5 switch(ls->bf) { case lh : root->bf = eh; rs->bf = rh; break; case eh : root->bf = rs->bf = eh; break; case rh : root->bf = lh; rs->bf = eh; break; } ls->bf = eh; root->right = rightrotate(rs); root = leftrotate(root); *taller = 0; } return(root); } /*---------------------End of function rightbalance---------------*/ /* FUNCTION TO BALANCE THE SUBTREE AT 'root' IF BALANCE FACTOR*/ /* AT 'root' IS DOUBLE LEFT HIGH */ struct node *leftbalance(struct node *root, int *taller) { struct node *ls = root->left, *rs; /*ASSIGN ls TO LEFT SUBTREE OF ROOT */ switch(ls->bf) { case lh : root->bf = ls->bf = eh; root = rightrotate( root); *taller = 0; break; case eh : printf("\n\tTREE ALREADY BALLANCED"); break; /* TREE IS ALREADY BALANCED */ case rh : rs = ls->right; /*ASSIGN rs RIGHT SUBTREE OF ls*/ switch(rs->bf) { case rh : root->bf = eh;

Comp Engg, AVCOE, Sangamner

6 ls->bf = lh; break; case eh : root->bf = ls->bf = eh; break; case lh : root->bf = rh; ls->bf = eh; break; } rs->bf = eh; root->left = leftrotate(ls); root = rightrotate(root); *taller = 0; } return(root); } /*----------------End of function leftbalance-----------------------*/ /* PROGRAM TO IMPLEMENT BINARY SEARCH TREE. program provides the operations for creating,searching,deletion and traversal . Program by: */

# include <stdio.h> /* HEADER FILES */ # include <conio.h> # include <dos.h> # include <string.h> # include <stdlib.h> struct node /* STRUCTURE FOR EACH NODE */ { char data[15]; struct node *left,*right; }; void insert(struct node *,struct node *); void tree(struct node *,int); /*-------------End of Declaration part------------------------------*/ void main() { int choice,c,i,flag; char temp='N',temp1[15]; struct node *s,*root,*r,*q; root=NULL; do {

Comp Engg, AVCOE, Sangamner

7 clrscr(); printf("\n 1.> ENTER "); printf("\n 2.> DELETE "); printf("\n 3.> SEARCH "); printf("\n 4.> DISPLAY ->"); printf("\n 5.> EXIT "); printf("\n\n Enter your choice :"); scanf("%d",&choice); switch(choice) { case 1: /* INSERTION OF NODE */ printf("****** DATA ENTRY ******\n"); do { s=malloc(sizeof(struct node)); s->left=NULL; s->right=NULL; printf("\n ENTER DATA : "); scanf("%s",&s->data); if(root==NULL) /* TREE EMPTY CONDITION */ root=s; else insert(root,s); printf("\n ENTER MORE ELEMENTS (Y/N) : "); scanf("\n%c",&temp); }while(temp=='y'); break; case 2: /* DELETION OPERATION */ printf("****** DELETE OPERATION ********\n"); do { printf("\n ENTER ELEMENT TO BE DELETED : "); scanf("%s",temp1); s=root;i=0;flag=0; do { if(strcmp(s->data,temp1)<0) { r=s; /* KEEPING TRACK OF PREVIOUS NODE */ s=s->right; i=1; } if(strcmp(s->data,temp1)>0) { r=s; s=s->left;

Comp Engg, AVCOE, Sangamner

8 i=2; } if(strcmp(s->data,temp1)==0) { flag=1; if(i==0) /* ROOT DELETION CONDITION */ { if(root->right!=NULL) { q=root->left; root=root->right; insert(root,q); } if(root->right==NULL) { root=root->left; } } else { if(i==1) /* NODE IS RIGHT TO PREVIOUS NODE*/ { q=s->left; r->right=s->right; if(s->left!=NULL) insert(r,q); } if(i==2) /* NODE IS LEFT TO PREVIOUS NODE*/ { q=s->right; r->left=s->left; if(s->right!=NULL) insert(r,q); } } } }while(flag==0&&s!=NULL); printf("\n DELETE ANY MORE (y/n) : "); scanf("\n%c",&temp); }while(temp=='y'); break; case 3: printf(" ****** SEARCH OPERATION ********\n\n "); do { printf("\n ENTER NAME TO BE SEARCHED : ");

Comp Engg, AVCOE, Sangamner

9 scanf("%s",temp1); i=0; s=root; while(s!=NULL&&i==0) { if(strcmp(s->data,temp1)<0) s=s->right; if(strcmp(s->data,temp1)>0) s=s->left; if(strcmp(s->data,temp1)==0) i=1; } if(i==0) /* ELEMENT NOT FOUND CONDITION */ printf("\n ELEMENT NOT FOUND \n"); else printf("\n ELEMENT FOUND\n"); printf("\n ENTER MORE ELEMENTS (Y/N) : "); scanf("\n%c",&temp); }while(temp=='y'); break; case 4: clrscr(); do { clrscr(); printf("\n 1.> PREORDER"); printf("\n 2.> INORDER"); printf("\n 3.> POSTORDER"); printf("\n 4.> NON-RECURSION"); printf("\n 5.> EXIT "); printf("\n Enter your choice :"); scanf("%d",&c); if(root==NULL) /* TREE EMPTY CONDITION */ printf("< TREE NOT STARTED YET >"); else tree(root,c); printf("\n\n PRESS ANY KEY TO CONTINUE ......"); getch(); }while(c!=5); break; } }while(choice!=5); } /*---------------End of Main function--------------------------------*/ void insert(struct node *r,struct node *p)

Comp Engg, AVCOE, Sangamner

10 /* FUNCTION FOR INSERTION */ { if((r->right==NULL)&&(strcmp(p->data,r->data)>0)) /* check whether new node is > root node */ { r->right=p; } else if((r->right!=NULL)&&(strcmp(p->data,r->data)>0)) { insert(r->right,p); /* RECURSIVE CALL*/ } if((r->left==NULL)&&(strcmp(p->data,r->data)<0)) { r->left=p; } else if((r->left!=NULL)&&(strcmp(p->data,r->data)<0)) { insert(r->left,p); /* RECURSIVE CALL */ } } /*--------------------End of function insert------------------------*/ void tree(struct node *r,int c) /* FUNCTION FOR TRAVERSAL */ { int top,flag; struct node *w,*stack[20]; if(r!=NULL) { if(c!=4) { if(c==1) printf(" %s ",r->data); tree(r->left,c); if(c==2) printf(" %s ",r->data); tree(r->right,c); if(c==3) printf(" %s ",r->data); } } if(c==4) /* NONRECURSIVE TRAVEL */ { top=0; w=r; flag=0; while(top!=-1&&w!=NULL)

Comp Engg, AVCOE, Sangamner

11 { while(flag==0&&w->left!=NULL) { stack[top]=w; top++; w=w->left; } printf(" %s ",w->data); if(w->right!=NULL) { w=w->right; flag=0; } else { top--; w=stack[top]; flag=1; } } } } /*------------------End of function tree --------------------*/ /*Program to implement circular queue using arrays This program uses kounter method, to keep track of the number of elements. Programmar */ #include<stdio.h> # define MAXSIZE 3 /* Define the maximum number of elments that you would like to place in the queue */ struct st{ int front,rear; int kount; int queue[MAXSIZE]; }; struct st s; /* A working variable s */ /*---------------------------------------------------------*/ /* Define the function prototypes, the basic operations that can be performed on the queue */ int empty(void); int full(void);

Comp Engg, AVCOE, Sangamner

12 void add(void); void delete(void); void display(void);

void main() { char ans; int ch; s.front=0; s.rear=-1; s.kount=0; do { clrscr(); printf("\t\t\tCIRCULAR QUEUE program\n"); /*Displaying Menu */ printf("\n\t\t 1> ADD\n"); printf("\n\t\t 2> DELETE\n"); printf("\n\t\t 3> DISPLAY\n"); printf("\n\t\t 4> QUIT\n"); printf("\n\t.......Enter your choice "); scanf("%d",&ch); switch(ch) { case 1 : add(); break; case 2 : delete(); break; case 3 : display(); break; case 4 : exit(1); break; default: printf("Wrong choice!!!!\n"); break; } printf("\n\t\tWnat to go to main menu ?[y/n] "); flushall(); ans = getch(); }while(ans == 'y' || ans == 'Y'); printf("\nPRESS ANY KEY TO EXIT ...\n"); getch(); } /* -----------END OF MAIN FUNCTION--------------------------------*/ int full(void)

Comp Engg, AVCOE, Sangamner

13 /* Function to check whether the queue is full or not. It returns a value 1 if true otherwise returns 0. */ { if (s.kount == MAXSIZE) return(1); else return(0); } /* -----------END OF FUNCTION full--------------------------------*/ int empty(void) /* Function to check whether the queue is empty or not. It returns a value 1 if true otherwise returns 0. */ { if (s.kount == 0) return(1); else return(0); } /* -----------END OF FUNCTION empty--------------------------------*/ void add(void) /* Function to add an element onto a queue */ { char ch; int x; do { if(full()==1) /* Check for queue full condition */ { printf("\n\n\t\tQueue Full !!!\n"); break; } else { s.rear = (s.rear + 1) % MAXSIZE; printf("\nEnter an element to be added "); scanf("%d",&x); s.queue[s.rear] = x; s.kount++; } printf("\n\tDo you want to add more elements? [y/n]"); flushall(); ch = getch(); }while(ch == 'y' || ch == 'Y'); } /* -----------END OF FUNCTION add--------------------------------*/ void delete(void) /* Function to delete an element off a queue */

Comp Engg, AVCOE, Sangamner

14 { char ch; do { if(empty()== 1) /* check for queue empty */ { printf("\n\n\t\tQueue Empty!!\n"); break; } else { printf("\t\t%d has been deleted!",s.queue[s.front]); s.front =(s.front+1) % MAXSIZE; s.kount--; } printf("\n\t\tDo you want to delete more ? [y/n] "); flushall(); ch = getch(); }while(ch == 'y' || ch == 'Y'); } /* -----------END OF FUNCTION delete--------------------------------*/ void display(void) /* Function to display queue elements */ { int i; clrscr(); if(empty()== 1) printf("\n\n\t\tQUEUE Empty!!!!"); else { printf("\n\n\t\tDisplaying queue....\n"); for(i = s.front; i <= s.rear; i++) printf("\n\t\t%d",s.queue[i]); } } /* -----------END OF FUNCTION display--------------------------------*/ /*TRAVERSAL OF A GRAPH By DFS*/ #include<stdio.h> #include<conio.h> #include<ctype.h> #include<stdlib.h> int mat(int adj[10][10]); void dfs(int adj[10][10],int no); void push(int j); int pop(void); void search(int adj[10][10],int j,int no);

Comp Engg, AVCOE, Sangamner

15 struct node { int num; struct node *next; }; struct node *p,*front,*rear; int v[10]; /*-------------------------End of declaration part----------------*/ void dfs1() { int adj[10][10],no,i,j; char resp; do { clrscr(); printf("\t***DFS TRAVERSAL***"); front = NULL; rear = NULL; for(i=0;i<10;i++) /*Visited array is set to indicate that no node is */ v[i] = 0; /*visited*/ for(i=0;i<10;i++) { for(j=0;j<10;j++) /*Adjacentcy matrix is initialized to 0*/ adj[i][j] = 0; } no = mat(adj); dfs(adj,no); do { printf("\n\nDO YOU WISH TO CONTINUE ?"); fflush(stdin); scanf("%c",&resp); resp = tolower(resp); }while(resp != 'y' && resp != 'n'); }while(resp != 'n'); } /*--------------End of function dfs-----------------------------*/ /*Function to create the adjacentcy matrix*/ int mat(int adj[10][10]) { int no,i,j; printf("\nENTER THE NO OF NODES IN GRAPH : "); scanf("%d",&no); if(no <= 1) { do {

Comp Engg, AVCOE, Sangamner

16 fflush(stdin); gotoxy(34,2); printf(" "); gotoxy(34,2); scanf("%d",&no); }while(no <= 1); } printf("\n\t\tCREATE THE ADJACENTCY MATRIX\n"); gotoxy(20,5); for(i=0;i<no;i++) printf("NODE%d ",i+1); gotoxy(10,7); for(i=0;i<no;i++) printf("\n\tNODE%d\n",i+1); for(i=0;i<no;i++) { for(j=0;j<no;j++) { gotoxy((20+(8*j)),(8+(2*i))); if(i==j) printf("0"); /*Indicate that no node is connected*/ else /*to itself*/ { adj[i][j] = 2; fflush(stdin); /*Error check -- only 1 or 0*/ scanf("%d",&adj[i][j]); /*can be entered by user*/ while(adj[i][j] != 0 && adj[i][j] != 1) { gotoxy((20+(8*j)),(8+(2*i))); printf(" "); gotoxy((20+(8*j)),(8+(2*i))); fflush(stdin); scanf("%d",&adj[i][j]); } } } } return(no); } /*---------------End of function mat-------------------------------*/ void dfs(int adj[10][10],int no) /* Function to implement dfs algorithm. */ { int i,j,flag=0; printf("\nORDER OF TRAVERSAL IS : \n"); i=0; while(flag != 1) {

Comp Engg, AVCOE, Sangamner

17 for(j=0;j<no;j++) /*Find a node in adjacentcy matrix which is */ { /*connected to some other node*/ if(adj[i][j] == 1) flag = 1; } i++; } if(i <= no) { push(i-1); j = i-1; v[j] = 1; printf("NODE%d ",j+1); j = pop(); for(i=1;i<no;i++) { if(adj[j][i] == 1) push(i); } search(adj,j,no); flag = -1; for(j = 0;j<no;j++) { if(v[j] != 1) flag = j; } if(flag != -1) printf("\nTHE GRAPH IS NOT CONNECTED"); getch(); } else printf("\nTHE GRAPH IS NOT CONNECTED"); } /*--------------------End of dfs function---------------------------*/ /*Push the currently working node while the adjacent nodes to it are visited*/ void push(int j) { p = malloc(sizeof(struct node)); p->num = j; p->next = NULL; if(front== rear && rear== NULL) { rear = p; front = p; } else {

Comp Engg, AVCOE, Sangamner

18 rear->next=p; rear = rear->next; } } /*-----------End of function push----------------------------------*/ /*Pop the node to continue traversal of a particular node*/ int pop() { int x; if(front != rear) { p = front; x = p->num; front = front->next; p->next = NULL; free(p); } else { p=front; x = p->num; free(p); front = NULL; rear = NULL; } return(x); } /*-------------------End of function pop---------------------------*/ void search(int adj[10][10],int i,int no) /* depthwise traversal */ { int j; for(j = 0;j<no;j++) { if(adj[i][j] == 1 && v[j] != 1) { /*Recursive function to traverse in depth*/ v[j] = 1; printf("NODE%d ",j+1); search(adj,j,no); } } } /*---------------------End of function search---------------------*/

Comp Engg, AVCOE, Sangamner

19 /* Polynomial Adddtion Using Generalised Linked Lists */ /* program by */ /* ------------------------------------------------- */ /* Including Header Files */ /* ---------------------- */ #include <stdio.h> #include <conio.h> #include <stdlib.h> #include <alloc.h> #include <ctype.h> /* Defining Global Variables */ /* ------------------------- */ typedef struct gll { int coefficent; int power; char variable; struct gll *down; struct gll *next; }GLL; GLL *first,*second,*result; int prev_exp_parsed=0; GLL *root=NULL; /* Defining Function Prototypes */ /* ---------------------------- */ int islegal(char ch); char *getstring(void); GLL *newnode(void); GLL *parse(char *polynomial); void print_polynomial(GLL *first); char *extract(char *polynomial,int *index); void add_polynomial(GLL *first ,GLL *second); int ismatch(GLL *first, GLL *second); void error(void); /* Main Manages Inputs & Outpuits */ /* ------------------------------ */ void main(void) { char *first_polynomial,*second_polynomial; clrscr(); printf("\n\n\tPolynomial Addition Using Generalised Linked List"); printf("\n\t-------------------------------------------------"); printf("\n\n\tEnter The First Polynomial: "); first_polynomial=getstring();

Comp Engg, AVCOE, Sangamner

20 printf("\n\n\tEnter The Second Polynomial: "); second_polynomial=getstring(); first=parse(first_polynomial); prev_exp_parsed=0; second=parse(second_polynomial); result=first; first=first->next; result->next=NULL; add_polynomial(result,first); add_polynomial(result,second); print_polynomial(result); } /* Checks For Illegal Characters */ /* ----------------------------- */ int islegal(char ch) { if(ch=='+' || ch=='^'|| ch=='\r' || isalnum(ch)) return 1; return 0; } /* Takes The String From The User */ /* ------------------------------ */ char *getstring(void) { int index=-1; char *string=(char *)malloc(100); do { index++; do *(string+index)=getch(); while(! (islegal(*(string+index))) ); putch(*(string+index)); }while(*(string+index)!='\r'); *(string+index)='\0'; return(string); } /* Creates A New Node */ /* ------------------ */ GLL *newnode(void) { GLL *temp=(GLL *)malloc(sizeof(GLL)); temp->down=temp->next=NULL;

Comp Engg, AVCOE, Sangamner

21 return(temp); } /* Converts String Polynomial To Linked List Polynomial */ /* ---------------------------------------------------- */ GLL *parse(char *polynomial) { GLL *temp=newnode(); int index=0, coefficent=1,power=1,count; int variable_found=0; char ans[5]; char *intermediate; while((*(polynomial+index))!='\0'&& !(prev_exp_parsed)) { if(isdigit(*(polynomial+index)) ) { count=0; while(isdigit(*(polynomial+index))) { ans[count++]=*(polynomial+index); index++; } if(count > 4) count=4; ans[count]='\0'; coefficent=atoi(ans); } if(isalpha(*(polynomial+index))) { if(!(variable_found)) { temp->variable=*(polynomial+index); index++; variable_found=1; } else { intermediate=extract(polynomial,&index); temp->down=parse(intermediate); } } if(*(polynomial+index)=='^') { if(!(variable_found)) error(); index++; if(isdigit(*(polynomial+index)) ) { count=0;

Comp Engg, AVCOE, Sangamner

22 while(isdigit(*(polynomial+index))) { ans[count++]=*(polynomial+index); index++; } if(count < 5) count=4; ans[count]='\0'; power=atoi(ans); } } if(*(polynomial+index)=='+') { index++; temp->coefficent=coefficent; temp->power=power; polynomial=polynomial+index; temp->next=parse(polynomial); prev_exp_parsed=1; } } temp->coefficent=coefficent; temp->power=power; return(temp); } /* Print The Polynomial From Generalised Linked List */ /* ------------------------------------------------- */ void print_polynomial(GLL *first) { int index=0,count=0,head_encountered=0; char ans[5]; GLL *temp1=first; char *polynomial=(char *)calloc(100,sizeof(char)); while(temp1!=NULL) { first=temp1; while(first!=NULL) { if(head_encountered==0) { count=0; if(first->coefficent!=1) { itoa(first->coefficent,ans,10); while(ans[count]!='\0') {

Comp Engg, AVCOE, Sangamner

23 *(polynomial+index)=ans[count]; count++;index++; } } head_encountered=1; } *(polynomial+index)=first->variable; index++; if(first->power!=1) { *(polynomial+index)='^'; index++; count=0; itoa(first->power,ans,10); while(ans[count]!='\0') { *(polynomial+index)=ans[count]; count++;index++; } } first=first->down; } temp1=temp1->next; head_encountered=0; if(temp1!=NULL) { *(polynomial+index)='+'; index++; } } *(polynomial+index)='\0'; printf("\n\n\tThe Final Answer Is %s",polynomial); getch(); } /* The Extract Will Create A Subterm Of The Polynomial */ /* --------------------------------------------------- */ char *extract(char *polynomial,int *index) { int count=0; char *new_polynomial=(char *)malloc(100); while( *(polynomial+(*index))!='+' && *(polynomial+(*index))!='\0') { *(new_polynomial+count)=*(polynomial+(*index)); (*index)++; count++; } *(new_polynomial+(count))='\0';

Comp Engg, AVCOE, Sangamner

24 return(new_polynomial); } /* This Function Will Add The Two Linked List Polynomial */ /* ----------------------------------------------------- */ void add_polynomial(GLL *first,GLL *second) { int match; GLL *temp,*temp1,*temp2; temp2=second; while(temp2!=NULL) { temp=first; match=0; while(temp!=NULL && match==0) { match=ismatch(temp,temp2); if(match==0) { temp1=temp; temp=temp->next; } } if(match==0) { temp1->next=temp2; temp2=temp2->next; temp1->next->next=NULL; } else { temp->coefficent+=temp2->coefficent; temp2=temp2->next; } } } /* This Will Check Weather Two Terms Are Of Same Degrees */ /* ----------------------------------------------------- */ int ismatch(GLL *first, GLL *second) { while(first!=NULL && second!=NULL) { if(first->power==second->power && first->variable==second->variable) { first=first->down; second=second->down; } else

Comp Engg, AVCOE, Sangamner

25 return 0; } if(first==NULL && second==NULL) return 1; else return 0; } /* This Function Will Show Error On Invalid Polynomial */ /* --------------------------------------------------- */ void error(void) { printf("\n\n\t\aERROR!!! "); printf("The Polynomial Is Not In Requested Form"); printf("\n\tThe Program Will Be Terminated..."); getch(); exit(1); } /* Polynomial Adddtion Using Generalised Linked Lists */ /* program by */ /* ------------------------------------------------- */ /* Including Header Files */ /* ---------------------- */ #include <stdio.h> #include <conio.h> #include <stdlib.h> #include <alloc.h> #include <ctype.h> /* Defining Global Variables */ /* ------------------------- */ typedef struct gll { int coefficent; int power; char variable; struct gll *down; struct gll *next; }GLL; GLL *first,*second,*result; int prev_exp_parsed=0; GLL *root=NULL; /* Defining Function Prototypes */ /* ---------------------------- */ int islegal(char ch); char *getstring(void); GLL *newnode(void);

Comp Engg, AVCOE, Sangamner

26 GLL *parse(char *polynomial); void print_polynomial(GLL *first); char *extract(char *polynomial,int *index); void add_polynomial(GLL *first ,GLL *second); int ismatch(GLL *first, GLL *second); void error(void); /* Main Manages Inputs & Outpuits */ /* ------------------------------ */ void main(void) { char *first_polynomial,*second_polynomial; clrscr(); printf("\n\n\tPolynomial Addition Using Generalised Linked List"); printf("\n\t-------------------------------------------------"); printf("\n\n\tEnter The First Polynomial: "); first_polynomial=getstring(); printf("\n\n\tEnter The Second Polynomial: "); second_polynomial=getstring(); first=parse(first_polynomial); prev_exp_parsed=0; second=parse(second_polynomial); result=first; first=first->next; result->next=NULL; add_polynomial(result,first); add_polynomial(result,second); print_polynomial(result); } /* Checks For Illegal Characters */ /* ----------------------------- */ int islegal(char ch) { if(ch=='+' || ch=='^'|| ch=='\r' || isalnum(ch)) return 1; return 0; } /* Takes The String From The User */ /* ------------------------------ */ char *getstring(void) { int index=-1; char *string=(char *)malloc(100); do {

Comp Engg, AVCOE, Sangamner

27 index++; do *(string+index)=getch(); while(! (islegal(*(string+index))) ); putch(*(string+index)); }while(*(string+index)!='\r'); *(string+index)='\0'; return(string); } /* Creates A New Node */ /* ------------------ */ GLL *newnode(void) { GLL *temp=(GLL *)malloc(sizeof(GLL)); temp->down=temp->next=NULL; return(temp); } /* Converts String Polynomial To Linked List Polynomial */ /* ---------------------------------------------------- */ GLL *parse(char *polynomial) { GLL *temp=newnode(); int index=0, coefficent=1,power=1,count; int variable_found=0; char ans[5]; char *intermediate; while((*(polynomial+index))!='\0'&& !(prev_exp_parsed)) { if(isdigit(*(polynomial+index)) ) { count=0; while(isdigit(*(polynomial+index))) { ans[count++]=*(polynomial+index); index++; } if(count > 4) count=4; ans[count]='\0'; coefficent=atoi(ans); } if(isalpha(*(polynomial+index))) { if(!(variable_found)) {

Comp Engg, AVCOE, Sangamner

28 temp->variable=*(polynomial+index); index++; variable_found=1; } else { intermediate=extract(polynomial,&index); temp->down=parse(intermediate); } } if(*(polynomial+index)=='^') { if(!(variable_found)) error(); index++; if(isdigit(*(polynomial+index)) ) { count=0; while(isdigit(*(polynomial+index))) { ans[count++]=*(polynomial+index); index++; } if(count < 5) count=4; ans[count]='\0'; power=atoi(ans); } } if(*(polynomial+index)=='+') { index++; temp->coefficent=coefficent; temp->power=power; polynomial=polynomial+index; temp->next=parse(polynomial); prev_exp_parsed=1; } } temp->coefficent=coefficent; temp->power=power; return(temp); } /* Print The Polynomial From Generalised Linked List */ /* ------------------------------------------------- */ void print_polynomial(GLL *first) { int index=0,count=0,head_encountered=0;

Comp Engg, AVCOE, Sangamner

29 char ans[5]; GLL *temp1=first; char *polynomial=(char *)calloc(100,sizeof(char)); while(temp1!=NULL) { first=temp1; while(first!=NULL) { if(head_encountered==0) { count=0; if(first->coefficent!=1) { itoa(first->coefficent,ans,10); while(ans[count]!='\0') { *(polynomial+index)=ans[count]; count++;index++; } } head_encountered=1; } *(polynomial+index)=first->variable; index++; if(first->power!=1) { *(polynomial+index)='^'; index++; count=0; itoa(first->power,ans,10); while(ans[count]!='\0') { *(polynomial+index)=ans[count]; count++;index++; } } first=first->down; } temp1=temp1->next; head_encountered=0; if(temp1!=NULL) { *(polynomial+index)='+'; index++; } } *(polynomial+index)='\0';

Comp Engg, AVCOE, Sangamner

30 printf("\n\n\tThe Final Answer Is %s",polynomial); getch(); } /* The Extract Will Create A Subterm Of The Polynomial */ /* --------------------------------------------------- */ char *extract(char *polynomial,int *index) { int count=0; char *new_polynomial=(char *)malloc(100); while( *(polynomial+(*index))!='+' && *(polynomial+(*index))!='\0') { *(new_polynomial+count)=*(polynomial+(*index)); (*index)++; count++; } *(new_polynomial+(count))='\0'; return(new_polynomial); } /* This Function Will Add The Two Linked List Polynomial */ /* ----------------------------------------------------- */ void add_polynomial(GLL *first,GLL *second) { int match; GLL *temp,*temp1,*temp2; temp2=second; while(temp2!=NULL) { temp=first; match=0; while(temp!=NULL && match==0) { match=ismatch(temp,temp2); if(match==0) { temp1=temp; temp=temp->next; } } if(match==0) { temp1->next=temp2; temp2=temp2->next; temp1->next->next=NULL; } else { temp->coefficent+=temp2->coefficent; temp2=temp2->next; }

Comp Engg, AVCOE, Sangamner

31 } } /* This Will Check Weather Two Terms Are Of Same Degrees */ /* ----------------------------------------------------- */ int ismatch(GLL *first, GLL *second) { while(first!=NULL && second!=NULL) { if(first->power==second->power && first->variable==second->variable) { first=first->down; second=second->down; } else return 0; } if(first==NULL && second==NULL) return 1; else return 0; } /* This Function Will Show Error On Invalid Polynomial */ /* --------------------------------------------------- */ void error(void) { printf("\n\n\t\aERROR!!! "); printf("The Polynomial Is Not In Requested Form"); printf("\n\tThe Program Will Be Terminated..."); getch(); exit(1); } /* Program to search a number from the linked list. We are using sequential search. Programmar :. */

#include<stdio.h> struct node { int no; struct node *next;

Comp Engg, AVCOE, Sangamner

32 }; struct node *root; /*------------------------Function to create the list---------------*/ void insert(int x) { struct node *p,*q; p=(struct node *)malloc(sizeof(struct node)); p->no=x; p->next=NULL; if (root==NULL) root=p; else { q=root; while(q->next !=NULL) q=q->next; q->next=p; } } /*--------------End of function insert-------------------------------*/ int search(int x) /* Function to search for x in the list */ { struct node *p; int k=0,found=0; p=root; if (p==NULL) { printf("\n Empty List "); return(k); } else { while ((p!=NULL) &&(found==0)) { k++; if(p->no==x) { found=1; } else p=p->next; } }

Comp Engg, AVCOE, Sangamner

33 if (found==0) k=0; return(k); } /*-------------End of function search-------------------------------*/ main() { int y,loc,opt; char ans; root=NULL; do { clrscr(); printf("\n\n\tLINEAR SEARCH FOR LINKED LIST"); printf("\n\t-----------------------------"); printf("\n\t\t1. Create the list "); printf("\n\t\t2. Search"); printf("\n\t\t3. exit"); printf("\n\n\t....Enter your choice :"); scanf("%d",&opt); switch(opt) { case 1: clrscr(); do { printf("\n Enter number to be inserted "); scanf("%d",&y); insert(y); printf("\n do you wish to add any more :"); ans=getch(); }while((ans=='y')||(ans=='Y')); break; case 2: clrscr(); printf("\n\t\t Enter the number to be searched "); scanf("%d",&y); loc=search(y); if(loc==0) printf("\n Number Not found "); else printf("\n The number %d is present in %d location ",y,loc); getch(); break; default : printf("\n Improper choice "); } }while (opt!=3);

Comp Engg, AVCOE, Sangamner

34 } /*----------------END OF MAIN FUNCTION---------------------------------------*/ /* Program to sort the numbers using MERGE SORT. Use the arrow keys to select the option . program by : */ /* Including Header Files */ /* ---------------------- */ #include <stdio.h> #include <stdlib.h> #include <conio.h> #include <alloc.h> /* Defining The Macros For Choices */ /* ------------------------------- */ #define CH1 "1.Create The List" #define CH2 "2.Sort The List " #define CH3 "3.Print The List " #define CH4 "4.Exit " #define CHOICE(ch) ch==1?CH1:(ch==2?CH2:(ch==3?CH3:CH4)) /* Function Prototypes */ /* ------------------- */ void append(void); void print(void); struct list *sort(struct list *p); struct list *divide(struct list *p); struct list *merge(struct list *p,struct list *q); /* Global Variable Definations */ /* --------------------------- */ struct list { int data; struct list *next; }; struct list *first; /* Function Main Displays Menu */ /* --------------------------- */ void main(void) { int ch=1,x; do {

Comp Engg, AVCOE, Sangamner

35 x=0; clrscr(); window(1,1,30,30); printf("\n\n\n\tMerge Sort On Linked Lists"); printf("\n\t--------------------------"); printf("\n\t1.Create The List"); printf("\n\t2.Sort The List"); printf("\n\t3.Print The List"); printf("\n\t4.Exit"); printf("\n\t---------------------"); printf("\n\tEnter Your Choice : "); printf("\n\t---------------------"); gotoxy(28,11); printf("%d",ch); gotoxy(9,5+ch); textcolor(BLACK); textbackground(WHITE); cprintf(CHOICE(ch)); while(x!=13) { fflush(stdin); x=getch(); gotoxy(9,5+ch); textcolor(WHITE); textbackground(BLACK); cprintf(CHOICE(ch)); if(x==80) ch=(ch < 4 ? ch+1 : 1); else if(x==72) ch=(ch > 1 ? ch-1 : 4); gotoxy(9,5+ch); textcolor(BLACK); textbackground(WHITE); cprintf(CHOICE(ch)); gotoxy(28,11); printf("%d",ch); } window(1,1,85,25); textcolor(WHITE); textbackground(BLACK); switch(ch) {

Comp Engg, AVCOE, Sangamner

36 case 1:append(); break; case 2:first=sort(first); break; case 3:print(); break; } }while(ch!=4); clrscr(); return; } /* Function For Appending Elements In List */ /* --------------------------------------- */ void append(void) { struct list *node,*last; int i,x,y; clrscr(); printf("\n\n\tEnter The No. Of Elements:"); x=scanf("%d",&y); if(x==0) return; while(first!=NULL) { last=first; first=first->next; last->next=NULL; free(last); } last=first; for(i=0;i<y;i++) { node=(struct list *)malloc(sizeof(struct list)); printf("\n\tEnter The Data at %d Th Location:",i+1); fflush(stdin); x=scanf("%d",&node->data); while(x==0) { printf("\n\tInput Error!!! Enter Again:"); fflush(stdin); x=scanf("%d",&node->data); }

Comp Engg, AVCOE, Sangamner

37 node->next=NULL; if(first==NULL) first=last=node; else { last->next=node; last=last->next; } } return; } /* Function For Displaying Linked List Elements */ /* -------------------------------------------- */ void print(void) { struct list *temp; int i=1,j=1; temp=first; clrscr(); printf("\n\n"); if(temp==NULL) printf("\tList Is Empty Now!!!"); while(temp!=NULL) { printf("\n\t%d %d",j,temp->data); temp=temp->next; i++; j++; if(i==21) { i=1; getch(); clrscr(); printf("\n\n"); } } getch(); return; } /* Function Sort Merge-Sorts The List */ /* ---------------------------------- */ struct list *sort(struct list *p) { struct list *q,*head;

Comp Engg, AVCOE, Sangamner

38

clrscr(); head=p; if(p!=NULL && p->next!=NULL) { q=divide(p); p=sort(p); q=sort(q); head=merge(p,q); } return(head); } /* Function Divide partitions The List in Two Sub List */ /* --------------------------------------------------- */ struct list *divide(struct list *p) { struct list *q,*r; q=p; r=p->next->next; while(r!=NULL) { r=r->next; q=q->next; if(r!=NULL) r=r->next; } r=q->next; q->next=NULL; return(r); } /* Function Merge Combines The Two Given Lists */ /* ------------------------------------------- */ struct list *merge(struct list *p,struct list *q) { struct list *head,*r; if(p==NULL || q==NULL) printf("merge called with empty list");

Comp Engg, AVCOE, Sangamner

39 if(p->data < q->data) { head=p; p=p->next; } else { head=q; q=q->next; } r=head; while(p!=NULL && q!=NULL) if(p->data < q->data) { r->next=p; r=r->next; p=p->next; } else { r->next=q; r=r->next; q=q->next; } if(p!=NULL) r->next=p; else r->next=q; return(head); } /* Program to add the polynomials using array. Make sure that the degrees are in an order. Program by : */ #include<stdio.h> #define MAX 5 #define MAX2 10 main() { int a[MAX],b[MAX],c[MAX2]; int m,n,i,nn,j,k; clrscr(); printf("\n Enter the degree of first polynomial :"); scanf("%d",&m);

Comp Engg, AVCOE, Sangamner

40

printf("\n Enter the degree of second polynomial :"); scanf("%d",&n); if((m>MAX)||(n>MAX)) { printf("\n Insufficient array size "); } else { printf("\n Enter the terms of first polynimial "); for(i=m-1;i>0;i--) { printf("\n Enter coefficient for x^[%d]",i); scanf("%d",&a[i]); } printf("\n Constant term "); scanf("%d",&a[0]); printf("\n Enter the terms of Second polynimial "); for(i=n-1;i>0;i--) { printf("\n Enter coefficient for x^[%d]",i); scanf("%d",&b[i]); } printf("\n Constant term "); scanf("%d",&b[0]); if (m<n) nn=m; else nn=n; k=0; for(i=0;i<nn;i++) { c[k]=a[i]+b[i]; k++; } if(m<n) /* copy from b in resultant ploy */ for(j=i;j<n;j++) { c[k]=b[j]; k++; } else for(j=i;j<m;j++) { c[k]=a[j]; k++; } clrscr(); printf("\n First polynomial is :\n\t\t");

Comp Engg, AVCOE, Sangamner

41 for(i=m-1;i>0;i--) printf(" %d x^%d +",a[i],i); printf("%d",a[0]); printf("\n Second polynomial is :\n\t\t"); for(i=n-1;i>0;i--) printf("%d x^%d +",b[i],i); printf("%d",b[0]); printf("\n\t\t Resultant polynomial is :\n\t\t"); for(i=k-1;i>0;i--) printf("%d x^%d +",c[i],i); printf("%d",c[0]); } getch(); } /*------------------------End of main -------------------*/

/* Program to find the minimum spanning tree of a weighted graph. Program by : */ #include<stdio.h> #include<stdlib.h> #define MAX 10 #define infinity 999 /* initial distance */ int t[MAX][MAX]; /*-------------end of function joinwt---------------------------------*/ int prims(cost,n) int cost[MAX][MAX],n; /* function to get the weights */ { int i,j,w,k,l,wt; int s[MAX]; int min=999,mincost=0; for(i=1;i<=n;i++) for(j=1;j<=n;j++) { if(cost[i][j] < min) { min=cost[i][j]; k=i; l=j; } } mincost=cost[k][l]; t[1][1]=k; t[1][2]=l;

Comp Engg, AVCOE, Sangamner

42 for(i=1;i<=n;i++) if (cost[i][l] <cost[i][k]) s[i]=l; else s[i]=k; s[k]=s[l]=0; for(j=2;j<n;j++) { w=find(cost,s,n); t[j][1]=w; t[j][2]=s[w]; mincost=mincost+cost[w][s[w]]; s[w]=0; for(k=1;k<=n;k++) if((s[k]!=0)&&(cost[k][s[k]] >cost[k][w])) s[k]=w; } return(mincost); } int find (int cost[MAX][MAX],int s [MAX],int n) { int min=999; int i,w=0; for(i=1;i<=n;i++) { if((s[i]!=0) && (cost[i][s[i]]<min)) { min=cost[i][s[i]]; w=i; } } return(w); } /*-------------------End of function-------------------------------*/ disp(int n) /* function to print the weight matrix */ { int i,j; for(i=1;i<n;i++) { for(j=1;j<=2;j++) printf("%d ",t[i][j]); printf("\n\n"); } } /*-------------------End of function mat--------------------------*/ main()

Comp Engg, AVCOE, Sangamner

43 { int cost[MAX][MAX]; int i,j,n,min=0; clrscr(); printf("\n\t\t How many nodes :"); scanf("%d",&n); printf("\n\t\t Enter the adjacency matrix of weight "); for(i=1;i<=n;i++) for(j=1;j<=n;j++) scanf("%d",&cost[i][j]); min=prims(cost,n); printf("\n Path :"); printf("\n The edges of the spanning tree :"); disp(n); printf("\minimum cost is %d",min); } /*---------------------End of main----------------------------------*/ /* Program to sort the list of names using Bubble sort. Here we reduce comparisons by 1 in each pass. Program By : */ #include<stdio.h> #include<string.h> #define MAX 10 char name[MAX][15]; /*-----------------------Function to sort names---------------*/ void sort(int n) /* Function takes number of names as argument and since array name is defined as global variable, we need not accept it from main() */ { int i,j,index; char temp[15]; for(i=n;i>0;i--) { strcpy(temp,name[1]); index=1; for(j=1;j<=i;j++) { if(strcmp(name[j],temp) > 0) /* if current name is greater than temp then store larger name */ { strcpy(temp,name[j]); index=j; } } strcpy(name[index],name[i]); strcpy(name[i],temp); }

Comp Engg, AVCOE, Sangamner

44 } /*-------------End of Function SORT------------------------------*/ main() { int n,i,j; clrscr(); printf("\n\t\t Enter how many names : "); scanf("%d",&n); if (n > MAX) printf("\n\t\t Array size is only %d",MAX); else { printf("\n\t\t Enter %d names ",n); for(i=1;i<=n;i++) /*accept the names */ { printf("\t\t"); scanf("%s",name[i]); } sort(n); /* call function to sort the names */ printf("\n\n\t\t SORTED LIST "); for(i=1;i<=n;i++) printf("\n\t\t%s",name[i]); } } /*--------------------End of the main function--------------*/ /* This program is to implement simple binary tree. We just create the tree and traverse it. Data here is names. # include <stdio.h> /* HEADER FILES */ # include <conio.h> # include <dos.h> # include <string.h> # include <stdlib.h> struct node /* STRUCTURE FOR EACH NODE */ { char data[15]; struct node *left,*right; }; void insert(struct node *,struct node *); void tree(struct node *,int); void main() { int choice,c,i,flag; char temp='N',temp1[15];

Comp Engg, AVCOE, Sangamner

45 struct node *s,*root,*r,*q; root=NULL; do { clrscr(); printf("\n\t\t 1.> ENTER "); printf("\n\t\t 2.> DISPLAY ->"); printf("\n\t\t 3.> EXIT "); printf("\n\n\t\t Enter your choice :"); scanf("%d",&choice); switch(choice) { case 1: root=NULL; /* INSERTION OF NODE */ printf("****** DATA ENTRY ******\n"); do { s=malloc(sizeof(struct node)); s->left=NULL; s->right=NULL; printf("\n ENTER DATA : "); scanf("%s",&s->data); if(root==NULL) /* TREE is empty */ root=s; else insert(root,s); printf("\n ENTER MORE ELEMENTS (Y/N) : "); scanf("\n%c",&temp); }while(temp=='y'); break; case 2: clrscr(); do{ clrscr(); printf("\n\t 1.> PREORDER"); printf("\n\t 2.> INORDER"); printf("\n\t 3.> POSTORDER"); printf("\n\t 4.> EXIT "); printf("\n\t Enter your choice :"); scanf("%d",&c); if(root==NULL) /* TREE EMPTY CONDITION */ printf("< TREE NOT STARTED YET >"); else tree(root,c); printf("\n\n PRESS ANY KEY TO CONTINUE ......"); getch(); }while(c!=4);

Comp Engg, AVCOE, Sangamner

46 break; } }while(choice!=3); } /*-------------------End of Main function----------------------------*/ void insert(struct node *r,struct node *p) /* FUNCTION FOR INSERTION */ { char ans; printf("\n wish to insert left/right of %s",r->data); ans=getch(); if ((ans=='r')||(ans=='R')) /* insert to right */ { if(r->right==NULL) { r->right=p; } else insert(r->right,p); } else /* insert left */ { if (r->left==NULL) { r->left=p; } else insert(r->left,p); /* RECURSIVE CALL*/ } } /*-------------End of insert function-------------------------------*/ void tree(struct node *r,int c) /* FUNCTION FOR TRAVERSAL */ { int top,flag; struct node *w,*stack[20]; if(r!=NULL) { if(c!=4) { if(c==1) printf(" %s ",r->data); tree(r->left,c); if(c==2) printf(" %s ",r->data); tree(r->right,c); if(c==3)

Comp Engg, AVCOE, Sangamner

47 printf(" %s ",r->data); } } } /*-------------------End of tree function---------------------------*/ /* PROGRAM FOR CREATION AND TRAVERSAL OF THREADED TREE . Uses complete thread. Program by : */

# include <stdio.h> /* HEADER FILES */ # include <conio.h> # include <dos.h> # include <stdlib.h> struct node /* STRUCTURE FOR EACH NODE */ { int info; int tleft,tright; struct node *left,*right; }; /*-----------------------End of declarations------------------------*/ void main() { int choice,flag; struct node *root,*s,*p,*q,*header=NULL; char cont; root=NULL; do { clrscr(); printf("\n\t\t ...... THREADED BINARY TREES ....... printf("\t 1.> ADD NEW ELEMENTS \n"); printf("\t 2.> INORDER TRAVERSAL\n"); printf("\t 3.> EXIT\n"); printf("\n \t\tENTER CHOICE : "); scanf("%d",&choice); /* CHOICE OF OPERATION */ switch(choice) { case 1: /* IF CHOICE IS INSERTION */ clrscr(); printf("\t\t\... DATA ENTRY OPERATION ...\n\n");

\n\n");

Comp Engg, AVCOE, Sangamner

48 do { s=malloc(sizeof(struct node)); printf("\n ENTER DATA : "); scanf("%d",&s->info); /* DATA TO BE ENTERED */ if(root==NULL) /* ROOT NULL CONDITION */ { root=s; root->right=header; root->left=header; root->tright=1; root->tleft=1; } else { q=root; flag=0; while(flag!=1) /* USING FLAG TO INDICATE INSERTED */ { if(q->info==s->info) { printf("\n%d ..already exists..",q->info); flag=1; } else { if(q->info < s->info&&q->tright==0) /* MOVING RIGHT */ { q=q->right; } else if(q->info > s->info && q->tleft==0) /* MOVING LEFT */ { q=q->left; } else if(q->info < s->info&&q->tright==1) { flag=1; } else

Comp Engg, AVCOE, Sangamner

49 if(q->info > s->info&&q->tleft==1) { flag=1; } } } if(q->info<s->info&&q->tright==1) /* IF INSERTION TO LEFT */ { p=q->right; q->right=s; q->tright=0; s->right=p; s->left=q; s->tright=1; s->tleft=1; } else if(q->info>s->info&&q->tleft==1) /* IF INSERTION TO RIGHT */ { p=q->left; q->left=s; q->tleft=0; s->left=p; s->right=q; s->tright=1; s->tleft=1; } } printf("\n ENTER MORE (y/n) : "); scanf("\n%c",&cont); }while(cont!='n'); /* CONDITION TO CONTINUE */ break; case 2: /* CHOICE TO TRAVEL */ clrscr(); printf(" ------ TRAVERSAL -----p=root; flag=0;

\n\n");

Comp Engg, AVCOE, Sangamner

50 while(p!=header) { while(flag==0&&p->tleft==0) { p=p->left; } printf(" %d ",p->info); if(p->tright==0) { p=p->right; flag=0; } else { p=p->right; flag=1; } } printf("\n\n PRESS ANY KEY TO MAIN MENU ......"); getch(); break; default : if(choice!=3) { printf("\n\n WRONG CHOICE RE-ENTER"); getch(); } break; } }while(choice!=3);/* CONDITION TO CONTINUE */ } /*------------------End of main function----------------------------*/ /* GRAPH TRAVERSAL USING BFS. The program includes a header file bfs.h, which defines the actual algorithm. The program is menu driven, use arrow keys for selecting the choices. In this program we have just created a menu and called bfs routine. Program by : */

Comp Engg, AVCOE, Sangamner

51 #include<stdio.h> #include<conio.h> #include<ctype.h> #include"d:\tc\bfs.h" void main(void) { char x; char menu[2][30]; int choice = 1, y; strcpy(menu[0],"1 : BFS TRAVERSAL"); /*Store Choices in menu*/ strcpy(menu[1],"2 : EXIT"); window(15,7,45,13); clrscr(); do { clrscr(); gotoxy(1,2); cprintf("%s",menu[1]); /* The choice of user is*/ /*highlighted on the screen*/ textbackground(15); textcolor(0); gotoxy(1,1); cprintf("%s",menu[0]); x = getch(); while(x != 13) /*13 is the ascii value of the enter key*/ { textbackground(0); textcolor(15); gotoxy(1,1); cprintf("%s",menu[0]); gotoxy(1,2); cprintf("%s", menu[1]); if(x == 80) /*If key pressed is down arrow */ { if(choice < 2) choice++; else choice = 1; } if(x == 72) /*If the key pressed is up arrow key*/ { if(choice > 1) choice--; else choice = 2; } gotoxy(1, choice);

Comp Engg, AVCOE, Sangamner

52 textbackground(15); textcolor(0); cprintf("%s",menu[choice-1]); flushall(); gotoxy(1,7); printf("YOUR CHOICE IS : "); cprintf("%d",choice); x = getch(); } textcolor(15); window(1,1,80,24); textbackground(0); switch(choice) { case 1 : bfs(); /* call the bfs function */ break; case 2 : clrscr(); printf("\nPRESS ANY KEY TO EXIT....."); getch(); } }while(choice != 2); } /*------------------End of Main----------------------------------------*/ /* Program to sort the list of names using Bubble sort. Here we reduce comparisons by 1 in each pass. */ #include<stdio.h> #include<string.h> #define MAX 10 char name[MAX][15]; /*-----------------------Function to sort names---------------*/ void sort(int n) /* Function takes number of names as argument and since array name is defined as global variable, we need not accept it from main() */ { int passes,comparisons; int i,j,k,kk; char temp[15]; passes=n-1; comparisons=n; kk=0; for(i=1;i<=passes;i++) { for(j=1;j<=comparisons-i;j++) { kk=kk+1;

Comp Engg, AVCOE, Sangamner

53 if(strcmp(name[j],name[j+1]) > 0) /* if first name is greater than second then swap */ { strcpy(temp,name[j]); strcpy(name[j],name[j+1]); strcpy(name[j+1],temp); } } printf("\n List after %d Pass is ",i); for(k=1;k<=n;k++) /* print list pass wise */ printf("\n\t\t %s",name[k]); getch(); } clrscr(); printf("\n \t\t Toatl comparisons done : %d",kk); } /*-------------End of Function SORT------------------------------*/

main() { int n,i,j; clrscr(); printf("\n\t\t Enter how many names : "); scanf("%d",&n); if (n > MAX) printf("\n\t\t Array size is only %d",MAX); else { printf("\n\t\t Enter %d names ",n); for(i=1;i<=n;i++) /*accept the names */ { printf("\t\t"); scanf("%s",name[i]); } sort(n); /* call function to sort the names */ printf("\n\n\t\t SORTED LIST "); for(i=1;i<=n;i++) printf("\n\t\t%s",name[i]); } } /*--------------------End of the main function--------------*/ /* Program to implement circular queue using linked list Note that the front is the pointer to point to the start of the queue.*/ #include<stdio.h>

Comp Engg, AVCOE, Sangamner

54 #include<stdlib.h> #include<conio.h> struct node { int info; struct node *next; }*p,*q,*front,*rear; void add_queue(void); void display_queue(void); void delete_queue(void); void main() { char ch,ch1; int y; front=NULL; rear=NULL; do /*Displaying Menu */ { clrscr(); printf("\t------CIRCULAR QUEUE USING LINKED LIST-------gotoxy(9,2); printf("1> ADD AN ELEMENT TO QUEUE\n\n"); printf("\t2> DISPLAY QUEUE\n\n"); printf("\t3> DELETE AN ELEMENT FROM QUEUE\n\n"); printf("\t4> QUIT"); gotoxy(9,2); for(;;) /* Loop for arrow keys */ { ch = getch(); if(ch == 13) break; if(ch == 0) { ch = getch(); if(ch == 80) { y = wherey(); gotoxy(9,y+2); } if(ch == 72) { y = wherey(); gotoxy(9,y-2); } } } switch(wherey())

\n");

Comp Engg, AVCOE, Sangamner

55 { case 2 : add_queue(); break; case 4 : display_queue(); break; case 6 : delete_queue(); break; case 8 : exit(1); break; default: printf("\nWrong choice!!!!\n"); break; } printf("\nWant to goto main menu ?[y/n]\n"); flushall(); ch1 = getch(); }while(ch1 == 'y' || ch1 == 'Y'); } /*------------------End of Main Program------------------------*/ void add_queue(void) /* Function to add an element to queue */ { char ch; clrscr(); p = malloc(sizeof(struct node)); printf("\n\n\n\tEnter data\n"); scanf("%d",&p->info); p->next = NULL; if(front == NULL) /* If this is the first element */ { front= p; rear=p; p->next=front; } else { rear->next=p; rear=rear->next; rear->next=front; } } /*---------------End of Function add--------------------------*/ void display_queue(void) /* Displaying the queue */ { clrscr(); q = front; if(q == NULL) /*Check for empty condition */ printf("\n THE QUEUE IS EMPTY\n"); else

Comp Engg, AVCOE, Sangamner

56 { printf("\n\t Queue Is :\n "); do { printf("\t%d ",q->info); q = q->next; } while(q!=front); } getch(); } /*------------End of Function Display-------------------------*/ void delete_queue(void) /* Deleting number from queue */ { int num; clrscr(); q = front; if(q == NULL) /* Check for empty condition */ printf("\n\n\t\tTHE QUEUE IS EMPTY!!\n"); else { printf("\n\t..Element deleted is %d",front->info); front=front->next; q->next=NULL; free(q); } } /*------------End of Function to Delete----------------------*/ /* Program to implement dll using linked list Programmar: */ #include<stdio.h> #include<stdlib.h> #include<conio.h> struct node { int info; struct node *rll,*ll; }*p,*q,*start,*r; void add_dll(void); void display_dll(void); void delete_dll(void); void main() { char ch,ch1;

Comp Engg, AVCOE, Sangamner

57 int y; start=NULL; do /*Displaying Menu */ { clrscr(); printf("\t------DLL USING LINKED LIST--------\n"); gotoxy(9,2); printf("1> ADD AN ELEMENT TO DLL\n\n"); printf("\t2> DISPLAY DLL\n\n"); printf("\t3> DELETE AN ELEMENT FROM DLL\n\n"); printf("\t4> QUIT"); gotoxy(9,2); for(;;) /* Loop for arrow keys */ { ch = getch(); if(ch == 13) break; if(ch == 0) { ch = getch(); if(ch == 80) { y = wherey(); gotoxy(9,y+2); } if(ch == 72) { y = wherey(); gotoxy(9,y-2); } } } switch(wherey()) { case 2 : add_dll(); break; case 4 : display_dll(); break; case 6 : delete_dll(); break; case 8 : exit(1); break; default: printf("\nWrong choice!!!!\n"); break; } printf("\nDo you want to continue?[y/n]\n"); flushall(); ch1 = getch(); }while(ch1 == 'y' || ch1 == 'Y');

Comp Engg, AVCOE, Sangamner

58 } /*-------End of Main----------------------------------------*/ void add_dll(void) /* Function to add an element to dll */ { char ch; clrscr(); p = malloc(sizeof(struct node)); printf("\n\n\n\tEnter data\n"); scanf("%d",&p->info); p->rll = NULL; p->ll=NULL; if(start == NULL) { start= p; } else { r=start; while(r->rll != NULL) r=r->rll; r->rll=p; p->ll=r; } } /*-------------------End of Function Add--------------------*/ void display_dll(void) /* Displaying the dll */ { clrscr(); q = start; if(q == NULL) /*Check for empty condition */ printf("\n THE DLL IS EMPTY\n"); else { printf("\n\n\n"); while(q !=NULL) { printf("%d\t",q->info); q = q->rll; } } getch(); } /*----------------End of display function-------------------*/ void delete_dll(void) /* Deleting number from dll */ { int num,found=0; clrscr();

Comp Engg, AVCOE, Sangamner

59 q = start; if(q == NULL) /* Check for empty condition */ printf("\n\nTHE DLL IS EMPTY!!\n"); else { printf("Enter the number to be deleted "); scanf("%d",&num); while ((found ==0 ) && (q != NULL)) { if (q->info == num ) found=1; else q=q->rll; } if (found==0) { printf("\n Number not found "); getch(); } else { if (q==start) { start=start->rll; q->rll=NULL; start->ll=NULL; free(q); } else { (q->rll)->ll=q->ll; ( q->ll)->rll=q->rll; q->ll=NULL; q->rll=NULL; free(q); } } } } /*---------------End of Delete function---------------------*/ /* Program to sort roll numbers in the list of student records,using heap sort method. #include<stdio.h> #define MAX 10 /* Maximum number of students */ void heapsort(int stud[],int n) /* Function for heap sort */ { int i,element,heap_pos,loc,ivalue; for(i=1;i<n;i++) /* create the initial heap */ { element=stud[i];

Comp Engg, AVCOE, Sangamner

60 heap_pos=i; /* insert the element in the descendind list in the path formed from the root to leaf i */

loc=(heap_pos-1)/2; while(heap_pos>0 && stud[loc]<element) { stud[heap_pos]=stud[loc]; heap_pos=loc; loc=(heap_pos-1)/2; } stud[heap_pos]=element; } for(i=n-1;i>0;i--) { ivalue=stud[i]; /* place first element in its proper position , adjust the heap */ /* find the larger node from a subtree delete it, and adjust the rest of tree */

stud[i]=stud[0]; loc=0; if(i==1) heap_pos=-1; else heap_pos=1; if(i>2 &&stud[2] > stud[1]) heap_pos=2; while(heap_pos>=0 && ivalue<stud[heap_pos]) { stud[loc]=stud[heap_pos]; loc=heap_pos; heap_pos=2*loc+1; if(heap_pos+1<=i-1 && stud[heap_pos]<stud[heap_pos+1]) heap_pos=heap_pos+1; if(heap_pos>i-1) heap_pos=-1; } stud[loc]=ivalue; } } /* ----------End of function heapsort----------------------------*/ main() { int n,i; int stud[MAX]; char ans; clrscr(); printf("\n Enter how many students "); scanf("%d",&n); if (n > MAX) printf("\n\t\t Sorry... Array size is less");

Comp Engg, AVCOE, Sangamner

61 else { printf("\n\t Enter The Records of %d students :",n); for(i=0;i<n;i++) { printf("\n Enter the Roll Number "); scanf("%d",&stud[i]); } clrscr(); heapsort(stud,n); do { for(i=0;i<n;i++) printf("\n %d",stud[i]); printf("\n\t\t Do you wish to search again"); ans=getch(); }while((ans=='y' || ans=='Y')); } } /*----------------------End of main-----------------------------------*/ /* This program is to find the largest number from a matrix of order m x n. #include<stdio.h> #define MAX 10 /*----------------------End of global declarations-------------------*/ main() { int a[MAX][MAX],i,j,m,n,large; clrscr(); printf("\nEnter the number of rows :"); scanf("%d",&m); printf("\nEnter the number of columns :"); scanf("%d",&n); if ((m>MAX ) || (n>MAX)) { printf("\n Number of elements exceed the limit "); } else { printf("\n Enter the %d elements : ",n); for(i=0;i<m;i++) for(j=0;j<n;j++) { printf("\n\t\t Enter a[%d][%d] : ",i,j); scanf("%d",&a[i][j]); } large=a[0][0]; /* assume the first number is largest */ for(i=0;i<m;i++)

Comp Engg, AVCOE, Sangamner

62 for(j=0;j<n;j++) { if (a[i][j] >large ) large=a[i][j]; } clrscr(); printf("\n\t\t The matrix is :\n"); for(i=0;i<m;i++) { printf("\t"); for(j=0;j<n;j++) { printf("\t %d",a[i][j]); } printf("\n"); } printf("\n\t\t Largest number is : %d",large); getch(); } } /*----------------------End of main----------------------------------*/ /*Program to implement queues using arrays. #include<stdio.h> # define MAXSIZE 10 /* Define the maximum number of elments that you would like to place in the queue */ struct st{ int front,rear; int queue[MAXSIZE]; }; /* Define a record two hold the primary entries : 1. Index top, and 2. An array to hold the elements the queue. */ struct st s; /* A working variable s */ /*---------------------------------------------------------*/ /* Define the function prototypes, the basic operations that can be performed on the queue */ int empty(void); int full(void); void add(void); void delete(void); void display(void);

void main() {

Comp Engg, AVCOE, Sangamner

63 char ans; int ch; s.front=0; s.rear=0; do { clrscr(); printf("\t\t\tQUEUE program\n"); /*Displaying Menu */ printf("\n\t\t 1> ADD\n"); printf("\n\t\t 2> DELETE\n"); printf("\n\t\t 3> DISPLAY\n"); printf("\n\t\t 4> QUIT\n"); printf("\n\t.......Enter your choice "); scanf("%d",&ch); switch(ch) { case 1 : add(); break; case 2 : delete(); break; case 3 : display(); break; case 4 : exit(1); break; default: printf("Wrong choice!!!!\n"); break; } printf("\n\t\tWnat to go to main menu ?[y/n] "); flushall(); ans = getch(); }while(ans == 'y' || ans == 'Y'); printf("\nPRESS ANY KEY TO EXIT ...\n"); getch(); } /* -----------END OF MAIN FUNCTION--------------------------------*/ int full(void) /* Function to check whether the queue is full or not. It returns a value 1 if true otherwise returns 0. */ { if (s.rear == MAXSIZE) return(1); else return(0);

Comp Engg, AVCOE, Sangamner

64 } /* -----------END OF FUNCTION full--------------------------------*/ int empty(void) /* Function to check whether the queue is empty or not. It returns a value 1 if true otherwise returns 0. */ { if (s.front == s.rear+1) return(1); else return(0); } /* -----------END OF FUNCTION empty--------------------------------*/ void add(void) /* Function to add an element onto a queue */ { char ch; int x; do { if(full()==1) /* Check for queue full condition */ { printf("\n\n\t\tQUEUE Full !!!\n"); break; } else { s.rear = s.rear + 1; printf("\nEnter an element to be added "); scanf("%d",&x); s.queue[s.rear] = x; if (s.rear==1) s.front++; } printf("\n\tDo you want to add more elements? [y/n]"); flushall(); ch = getch(); }while(ch == 'y' || ch == 'Y'); } /* -----------END OF FUNCTION add--------------------------------*/ void delete(void) /* Function to delete an element off a queue */ { char ch; do { if(empty()== 1) /* check for queue empty */ {

Comp Engg, AVCOE, Sangamner

65 printf("\n\n\t\tQueue Empty!!\n"); break; } else { printf("\t\t%d has been deleted!",s.queue[s.front]); s.front = s.front+1; } printf("\n\t\tDo you want to delete more ? [y/n] "); flushall(); ch = getch(); }while(ch == 'y' || ch == 'Y'); } /* -----------END OF FUNCTION delete--------------------------------*/ void display(void) /* Function to display queue elements */ { int i; clrscr(); if(empty()== 1) printf("\n\n\t\tQUEUE Empty!!!!"); else { printf("\n\n\t\tDisplaying queue....\n"); for(i = s.front; i < s.rear+1; i++) printf("\n\t\t%d",s.queue[i]); } } /* -----------END OF FUNCTION display--------------------------------*/

/* To add two polynomials using linked lists . Prgrammer : */ #include<stdio.h> #include<conio.h> #include<stdlib.h> struct node { int x,c; struct node *next; } *p,*q,*r3,*r,*s; struct node * poly_create(struct node *r1) /* Function to create a polynomial */ { int n,i; printf("How many entries? : "); scanf("%d",&n); for(i=0;i<n;i++)

Comp Engg, AVCOE, Sangamner

66 { p=malloc(sizeof(struct node)); p->next=NULL; printf("Exponent = "); scanf("%d",&p->x); printf("Coefficient = "); scanf("%d",&p->c); if(r1==NULL) { r1=p; /* p is the first element */ } else { r=r1; while(r->next!=NULL) r=r->next; /* find out the last element*/ r->next=p; } } return(r1); } /*-------------- End of Function craeting the polynomial---- */ void disp(struct node *r1) { struct node *rr; rr=NULL; rr=r1; printf("\t\t"); do { if(rr->c !=0) /* Display only nonzero coefficients */ { if(rr->x !=0) printf("%dx^%d + ",rr->c,rr->x); else printf("%d + ",rr->c);/*Don't display a zero exponent*/ } rr=rr->next; }while(rr->next!=NULL); if(rr->c !=0) { if(rr->x !=0) printf("%dx^%d ",rr->c,rr->x); else printf("%d ",rr->c); } }

Comp Engg, AVCOE, Sangamner

67 /*----------------End of Display Function-------------*/ main() { int choice,flag=0,i; struct node *a,*b; char ans; clrscr(); a=NULL;b=NULL; do { clrscr(); printf("\t\tProgram to add two polynomials\n"); printf("\t\t 1.Create two polynomials\n"); printf("\t\t 2.Adding two polynomials\n"); printf("\t\t 3.Exit\n"); printf("\n\tEnter Your Choice "); scanf("%d",&choice); switch(choice) { case 1: printf("\n\t\tFirst polynomial\n"); printf("Enter exponents in decreasing order\n"); a=poly_create(a);/*Create first polynomial*/ printf("\t\tSecond polynomial\n"); b=poly_create(b);/* Create second polynomial*/ clrscr(); printf("\n\t\t Yor Two Polynomials are :\n"); printf("FIRST POLYNOMIAL :\n"); disp(a); printf("\nSECOND POLYNOMIAL :\n"); disp(b); getch(); break; case 2: printf("\n\t\t Result is\n"); p=a; q=b; while((p!=NULL)||(q!=NULL)) { s=malloc(sizeof(struct node)); s->next=NULL; if(p->x==q->x) { s->c=p->c+q->c; s->x=p->x; if(p!=NULL) { p=p->next; } if(q!=NULL) {

Comp Engg, AVCOE, Sangamner

68 q=q->next; } flag=1; } else { if(p->x < q->x) { s->c=q->c; s->x=q->x; if(q!=NULL) { q=q->next; } flag=1; } else { s->c=p->c; s->x=p->x; if(p!=NULL) { p=p->next; } flag=1; } } if(flag==1) { if(r3==NULL) r3=s; else { r=r3; while(r->next!=NULL) r=r->next; r->next=s; } } } disp(r3); getch(); break; default: break; } }while(choice !=3);

Comp Engg, AVCOE, Sangamner

69 } /*---------------End Of Main------------------------------------*/ /* Program to evaluate POSTFIX EXPRESSION . # include<stdio.h> # include<ctype.h> # include<conio.h> # include<string.h> # include<math.h> void push(float , int *, float []); float pop(int *,float []); /*--------------End of global declarations/definitions---------------*/ void main(void) { char exp[50],str[10],c; int i, j = 0,l, *t = 0, done = 0; float x[4], stack[10]; clrscr(); strset(exp,'\0'); printf("ENTER THE EXPRESSION "); printf("\n Enter blank between each operand or operator \n\t\t"); flushall(); gets(exp); l = strlen(exp); strset(str,'\0'); /* INITIALIZE 'str'*/ for(i = 0; i<l; i++) { c = exp[i]; if( isalpha(c) || iscntrl(c)) /* ERROR CHECK */ { printf("\n\n\t\tINVALID EXPRESSION !"); done = 1; break; } else if( c != ' ' && isdigit(c)) /* IF OPERAND ENCOUNTERED ADD TO 'str' */ { str[j] = c; j++; } else if( c == ' ' && str[0] != '\0') { x[0] = atof(str); /* GET THE OPERAND */ push(x[0],t,stack); /* PUSH OPERAND ONTO STACK */ strset(str,'\0'); /* INITIALIZE 'str'*/ j = 0; }

Comp Engg, AVCOE, Sangamner

70 else if(!(isdigit(c)) && c != ' ') /* IF OPERATOR ENCOUNTERED POP TWICE */ { /* FROM STACK AND PERFORM RELEVANT OPERATION*/ x[2] = pop(t,stack); x[1] = pop(t,stack); switch(c) { case '+' : x[3] = x[1] + x[2]; push(x[3],t,stack); break; case '-' : x[3] = x[1] - x[2]; push(x[3],t,stack); break; case '*' : x[3] = x[1] * x[2]; push(x[3],t,stack); break; case '/' : x[3] = x[1] / x[2]; push(x[3],t,stack); break; case '^' : x[3] = pow(x[1] , x[2]); push(x[3],t,stack); break; } } } x[3] = pop(t,stack); /* POP ANSWER FROM STACK */ if(done == 0) printf("result : %.5f",x[3]); getch(); } /*-------------------End of main function---------------------------*/ void push(float s, int *t, float st[]) /* function to PUSH element onto stack s */ { *t = *t+1; st[*t] = s; } /*--------------End of function push-------------------------------*/

Comp Engg, AVCOE, Sangamner

71

float pop(int *t,float st[]) /* Function to pop the elements from stack */ { float s; s = st[*t]; *t = *t-1; return(s); } /*------------end of function pop---------------------------------*/ /* Program to implement queue using linked list Note that the start and rear are the two pointers to point to the start and end of the queue. Programmar : Mrs. Shivangi. G. Potdar #include<stdio.h> #include<stdlib.h> #include<conio.h> struct node { int info; struct node *rll,*ll; }*p,*q,*start,*r; void add_queue(void); void display_queue(void); void delete_queue(void); void main() { char ch,ch1; int y; start=NULL; do /*Displaying Menu */ { clrscr(); printf("\t------QUEUE USING LINKED LIST--------\n"); gotoxy(9,2); printf("1> ADD AN ELEMENT TO QUEUE\n\n"); printf("\t2> DISPLAY QUEUE\n\n"); printf("\t3> DELETE AN ELEMENT FROM QUEUE\n\n"); printf("\t4> QUIT"); gotoxy(9,2); for(;;) /* Loop for arrow keys */ { ch = getch(); if(ch == 13) break; */

Comp Engg, AVCOE, Sangamner

72 if(ch == 0) { ch = getch(); if(ch == 80) { y = wherey(); gotoxy(9,y+2); } if(ch == 72) { y = wherey(); gotoxy(9,y-2); } } } switch(wherey()) { case 2 : add_queue(); break; case 4 : display_queue(); break; case 6 : delete_queue(); break; case 8 : exit(1); break; default: printf("\nWrong choice!!!!\n"); break; } printf("\nDo you want to continue?[y/n]\n"); flushall(); ch1 = getch(); }while(ch1 == 'y' || ch1 == 'Y'); } void add_queue(void) /* Function to add an element to queue */ { char ch; clrscr(); p = malloc(sizeof(struct node)); printf("\n\n\n\tEnter data\n"); scanf("%d",&p->info); p->rll = NULL; p->ll=NULL; if(start == NULL) { start= p; } else

Comp Engg, AVCOE, Sangamner

73 { r=start; while(r->rll != NULL) r=r->rll; r->rll=p; p->ll=r;

} } void display_queue(void) /* Displaying the queue */ { clrscr(); q = start; if(q == NULL) /*Check for empty condition */ printf("\n THE QUEUE IS EMPTY\n"); else { printf("\n\n\n"); while(q !=NULL) { printf("%d\t",q->info); q = q->rll; } } getch(); } void delete_queue(void) /* Deleting number from queue */ { int num,found=0; clrscr(); q = start; if(q == NULL) /* Check for empty condition */ printf("\n\nTHE QUEUE IS EMPTY!!\n"); else { printf("Enter the number to be deleted "); scanf("%d",&num); while ((found ==0 ) && (q != NULL)) { if (q->info == num ) found=1; else q=q->rll; } if (found==0) { printf("\n Number not found "); getch(); } else { if (q==start) {

Comp Engg, AVCOE, Sangamner

74 start=start->rll; q->rll=NULL; start->ll=NULL; free(q); } else { (q->rll)->ll=q->ll; ( q->ll)->rll=q->rll; q->ll=NULL; q->rll=NULL; free(q); } } } } /* Program to implement primitive operations on Sequential files. The input record contains : name of student, rollnumber and three test scores. /*----------------------------------------------------------------------*/ /*Header Files*/ #include<stdio.h> #include<conio.h> #include<stdlib.h> #include<string.h> /*structure declaration*/ typedef struct record { int roll,m1,m2,m3; /* m1,m2,m3 are the three test scores */ char name[30]; }stud; FILE *fp; /*------------end of global variable declarations----------*/ void display(); void append(); void create(); void sort(FILE *); void display_one(stud ,int ); void input_rec(FILE *); int search(char filename[]); void delete_rec(char filename[]); void index(char[]); /*----------Function prototype declaration ends------------*/ main() {

Comp Engg, AVCOE, Sangamner

75 char ans,filename[12]; int ch; do { clrscr(); printf("\n\t\tINDEXED SEQUENTIAL FILE"); printf("\n\t 1>Create a file"); printf("\n\t 2>Add a record"); printf("\n\t 3>Search for Record"); printf("\n\t 4>Display file"); printf("\n\t 5>Quit"); printf("\n\t\t Enter your choice"); scanf("%d",&ch); switch(ch) { case 1 : clrscr(); create(); break; case 2 : clrscr(); append(); break; case 3 : clrscr(); printf("\nEnter the filename\n"); flushall(); gets(filename); search(filename); break; case 4 : clrscr(); display(); break; case 5 : clrscr(); exit(1); break; default: printf("\nEntered wrong choice\n"); break; } printf("\nDo you want to continue?[y/n]"); flushall(); ans = getch(); }while(ans == 'y' || ans == 'Y'); } /*-----------------End of main function-----------------------------*/

Comp Engg, AVCOE, Sangamner

76 void create() /*Function to create a new file*/ { char filename[12]; printf("\n\tEnter the filename in which you wish to store data\n"); flushall(); gets(filename); if((fp = fopen(filename,"wb")) == NULL) { printf("ERROR in opening file in write mode"); return; } input_rec(fp); /* get records in file */ fclose(fp); if((fp = fopen(filename,"rb+")) == NULL) { printf("Error in opening file in read mode"); return; } } /*------------End of function create---------------------------------*/ void input_rec(FILE *fp) /*Accept data for record*/ { stud temp; char ch; int i = 1; do { clrscr(); printf("\n\n\tRecord No. %d",i); printf("\n\n\tStudent Name :"); fflush(stdin); gets(temp.name); printf("\n\n\tRoll number :"); scanf("%d",&temp.roll); printf("\n\n\tMarks 1 :"); scanf("%d",&temp.m1); printf("\n\n\tMarks 2 :"); scanf("%d",&temp.m2); printf("\n\n\tMarks 3 :"); scanf("%d",&temp.m3); fwrite(&temp,sizeof(stud),1,fp); i++; printf("\nDo you wish to continue adding records?[y/n]"); flushall(); ch = getch();

Comp Engg, AVCOE, Sangamner

77 }while(ch == 'y' || ch == 'Y'); } /*---------------End of function input_rec---------------------------*/ void append() /*Appending the exisiting file*/ { char filename[12]; printf("\nEnter the filename\n"); flushall(); gets(filename); if((fp = fopen(filename,"ab")) == NULL) { printf("ERROR in opening file"); return; } printf("\nAppending File"); getch(); input_rec(fp); fclose(fp); if((fp = fopen(filename,"rb+")) == NULL) { printf("Error in opening file"); return; } } /*----------------end of append function----------------------------*/ void display() /*displaying the file*/ { char filename[12]; int i = 1; stud temp; printf("\nEnter the filename\n"); flushall(); gets(filename); if((fp = fopen(filename,"rb")) == NULL) { printf("\nError in opening file"); return; } fread(&temp,sizeof(stud),1,fp); while(!feof(fp)) { clrscr(); printf("\nRecords of file '%s'",filename); printf("\n\n\tRecord %d",i); printf("\n\n\tStudent Name : %s",temp.name);

Comp Engg, AVCOE, Sangamner

78 printf("\n\n\tRoll Number : %d",temp.roll); printf("\n\n\tMarks 1 : %d",temp.m1); printf("\n\n\tMarks 2 : %d",temp.m2); printf("\n\n\tMarks 3 : %d",temp.m3); i++; getch(); fread(&temp,sizeof(stud),1,fp); printf("Enter to continue...."); } fclose(fp); } /*---------------------------End of function DISPLAY----------------*/ int search(char filename[]) /*searching for required record*/ { int found=0,rno,key,pos = 0,kk; stud temp; if((fp = fopen(filename,"rb")) == NULL) { printf("\nError in opening File"); return; } printf("\nEnter The roll number of record to be found\n"); scanf("%d",&rno); while((!found)&&(!feof(fp))) { fread(&temp,sizeof(stud),1,fp); if(temp.roll == rno) /* get the record for required key */ found = 1; } if(found == 1) { display_one(temp,pos); return(pos); } else { printf("\nRecord not found"); fclose(fp); return(-1); } } /*---------------End of search function-----------------------------*/ void display_one(stud temp,int pos) /*display the record which "search" function has found */

Comp Engg, AVCOE, Sangamner

79 { clrscr(); printf("\n\n\tRecord %d",pos); printf("\n\n\tStudent Name : %s",temp.name); printf("\n\n\tRoll Number : %d",temp.roll); printf("\n\n\tMarks 1 : %d",temp.m1); printf("\n\n\tMarks 2 : %d",temp.m2); printf("\n\n\tMarks 3 : %d",temp.m3); getch(); printf("Enter to continue...."); } /*---------------End of display function of single record------------*/ /* Program to add the sparse matrices #include<stdio.h> #define MAX 10 struct trio { int nr,nc,val; int flag; }; struct trio a[MAX],b[MAX],c[MAX]; main() { int m1,n1,m2,n2; int k,t,kk,nt,i,t1,t2,j; clrscr(); printf("\n Enter order of first matrix :"); scanf("%d %d",&m1,&n1); printf("\n Enter order of second matrix :"); scanf("%d %d",&m2,&n2); printf("\n enter how many nonzero elements of A:"); scanf("%d",&k); for(i=1;i<=k;i++) { printf("\n Enter row,column and the value :"); scanf("%d %d %d",&a[i].nr,&a[i].nc,&a[i].val); a[i].flag=0; } printf("\n enter how many nonzero elements of B:"); scanf("%d",&kk); for(i=1;i<=kk;i++) { printf("\n Enter row,column and the value :");

Comp Engg, AVCOE, Sangamner

80 scanf("%d %d %d",&b[i].nr,&b[i].nc,&b[i].val); b[i].flag=0; } if(k>kk) { t1=k; t2=kk; } else { t1=kk; t2=k; } nt=0; for(i=1;i<=t2;i++) { for(j=1;j<=t1;j++) { if((a[i].nr ==b[j].nr)&&(a[i].nc==b[j].nc)&&(a[i].flag==0)&&(b[j].flag==0)) { nt++; c[nt].nr=a[i].nr; c[nt].nc=a[i].nc; c[nt].val=a[i].val+b[i].val; a[i].flag=1; b[i].flag=1; printf("\n nt %d",nt); } } } for(i=1;i<=k;i++) if(a[i].flag!=1) { nt++; c[nt].nr=a[i].nr; c[nt].nc=a[i].nc; c[nt].val=a[i].val; } for(i=1;i<=kk;i++) if(b[i].flag!=1) { nt++; c[nt].nr=b[i].nr; c[nt].nc=b[i].nc; c[nt].val=b[i].val; } printf("\n The resulting matrix :\n");

Comp Engg, AVCOE, Sangamner

81 printf("\n The non zero elements only :\n"); for(i=1;i<=nt;i++) printf("row %d column %d value %d\n",c[i].nr,c[i].nc,c[i].val); } /*--------------------End of main----------------------------------------*/

You might also like