SlideShare uma empresa Scribd logo
1 de 78
Ex no –1(A)       IMPLEMENTATION OF SINGLY
                       LINKED LIST
AIM:
       To write a c program to implement singly linked list.

ALGORITHM:
       Step1: Start the program.

       Step2: Include the required header files at the top of the program.

       Step3: Create a structure named node and declare variables to denote a node for

               singly linked list.

       Step4: In the create () method, check whether the head is NULL or not. If it is

               NULL, then get the number of nodes from user and get data for each

               node that are created.

       Step5: In the insert () method, check whether the head is NULL or not. If it is

               NOT NULL, then get the position from the user and then insert into list.

       Step6: In the delete () method, check whether the head is NULL or not. If it is

               NOT NULL, then get the position to be deleted from the user.

       Step7: Insert and delete according to the position.

       Step8: In display () method, print the elements of singly linked list.

       Step9: In main () method, use switch case statement to invoke the methods

               according to the user choice entered.

       Step10: End of the program.




                                            1
PROGRAM:
#include<conio.h>
#include<stdio.h>
void creation(int);
void display();
void insertion(int,int);
void deletion(int);
struct list
{
  int num;
  struct list *next;
}*head, *l;
void main()
{
  int n1,ch,pos,val;
  clrscr();
  do
  {
    printf("n1.creationn2.insertionn3.deletionn4.displayn5.exitn");
    printf("nenter ur choice : ");
    scanf("%d",&ch);
    switch(ch)
    {
         case 1:
                 creation(n1);
                 break;
         case 2:
                 printf("nnenter the postion in which to be inserted : ");
                 scanf("%d",&pos);
                 printf("nnenter the value : ");
                 scanf("%d",&val);
                 insertion(pos,val);
                 break;
         case 3:
                 printf("nnenter the position to be deleted : ");
                 scanf("%d",&pos);
                 deletion(pos);
                 break;
         case 4:
                 display();
                 getch();
                 break;
         case 5:
                 exit(0);
    }
  }while(ch!=5);

                                               2
getch();
}
void creation(int n1)
{
  int i,n;
  head=((struct list *)malloc(sizeof(struct list)));
  l=head;
  printf("nEnter the no of nodes:");
  scanf("%d",&n1);
  for(i=0;i<n1;i++)
  {
     printf("enter the %d node : ",i+1);
     scanf("%d",&n);
     l->num=n;
     l->next=((struct list *)malloc(sizeof(struct list)));
     l=l->next;
  }
  l->next=0;
}
void display()
{
  l=head;
  printf("nthe nodes entered are : ");
  while(l->next>0)
  {
    printf("%dt",l->num);
    l=l->next;
  }
  printf("null");
}
void insertion(pos,val)
{
  int i;
  struct list *x,*y;
  l=head;
  i=2;
  if(pos==1)
  {
    x=((struct list *)malloc(sizeof(struct list)));
    x->num=val;
    x->next=l;
    head=x;
  }
  else
  {
          while(l->next>0)

                                                 3
{
           if(pos==i-1)
           {
             x=((struct list *)malloc(sizeof(struct list)));
             x->num=val;
             x->next=l;
             y->next=x;
           }
           y=l;
           l=l->next;
           i++;
       }
  }
}
void deletion(pos)
{
  int i;
  struct list *y;
  l=head;
  i=1;
  if(pos==1)
  { head=l->next; }
  else
  {
    while(l->next>0)
    {
      if(pos==i)
      { l=l->next;
          y->next=l;
          break;
      }
      y=l;
      l=l->next;
      i++;
    }
  }
}




                                                4
INPUT & OUTPUT:

1.creation
2.insertion
3.deletion
4.display
5.exit
enter ur choice : 1
Enter the no of nodes:2
enter the 1 node : 1
enter the 2 node : 2

1.creation
2.insertion
3.deletion
4.display
5.exit
enter ur choice : 2
enter the postion in which to be inserted : 1
enter the value : 6

1.creation
2.insertion
3.deletion
4.display
5.exit
enter ur choice : 4
the nodes entered are : 6    1     2     null

1.creation
2.insertion
3.deletion
4.display
5.exit
enter ur choice : 2
enter the postion in which to be inserted : 2
enter the value : 4

1.creation
2.insertion
3.deletion
4.display
5.exit
enter ur choice :2

enter the postion in which to be inserted : 2

                                                5
enter the value : 4

1.creation
2.insertion
3.deletion
4.display
5.exit
enter ur choice : 3
enter the position to be deleted : 2

1.creation
2.insertion
3.deletion
4.display
5.exit
enter ur choice : 4
the nodes entered are : 6      1       2   null

1.creation
2.insertion
3.deletion
4.display
5.exit
enter ur choice : 5<Exiting>




RESULT:

      Thus the program for program for implementation of singly linked list has been
completed successfully and output verified.

Ex no –1(B)           IMPLEMENTATION OF DOUBLY
                                                  6
LINKED LIST
AIM:
       To write a c program to implement doubly linked list.

ALGORITHM:
       Step1: Start the program.

       Step2: Include the required header files at the top of the program.

       Step3: Create a structure named node and declare variables to denote a node for

                doubly linked list.

       Step4: In the create () method, get the number of nodes and iterate the loop to

                get data for each node that are created.

       Step5: In the insert () method, get the position from the user. If it is valid

                position, get the data for a node and give forward link and backward link.

       Step6: In the delete () method, get the position to be deleted. If it is valid

                position, by rearranging forward link and backward link to delete the

                node from the list.

       Step7: Insert and delete according to the valid position.

       Step8: In display () method, print the elements of doubly linked list.

       Step9: In main () method, use switch case statement to invoke the methods

                according to the user choice entered.

       Step10: End of the program.




PROGRAM:
#include<stdio.h>
                                             7
#include<conio.h>
struct list
{
int data;
struct list *llink,*rlink;
};
typedef struct list node;
node *head=NULL, *tail=NULL;
void ins(node *head)
{
node *p,*q;
int d,t;
q=(node*)malloc( sizeof(node) );
printf("enter the element into the list :");
scanf("%d" ,&d);
q->data=d;
q->rlink=q-> llink=NULL;
p=head;
do
{
if(p->rlink->llink==NULL)
{ q->llink=head;
head->rlink= q;
q->rlink=tail;
tail->llink= q;
t=1;
}
else
if(p->rlink->data>d)
{
p->rlink->llink= q;
q->llink=p;
q->rlink=p-> rlink;
p->rlink=q;
t=1;
}
else
p=p->rlink;
}
while(t!=1);
while(p->llink!=NULL)
p=p->llink;
head=p;
}
void delete(node *head)
{

                                               8
int d,t;
node *p, *fntptr;
printf("enter the deleted element :");
scanf("%d",& d);
p=head;
do
{
fntptr=p->rlink;
if(p->rlink->data==d)
{
fntptr=fntptr->rlink;
p->rlink=fntptr;
fntptr=p;
t=1;
}
else
if(d>p->rlink->data)
p=fntptr;
else
{
puts("n data not found n");
t=1;
}
}
while(t!=1);
while(p->llink!=NULL)
p=p->llink;
head=p;
}
void dis(node *head)
{
node *p;
p=head->rlink;
while(p->rlink!=NULL)
{
printf("%d-> ",p->data) ;
p=p->rlink;
}
while(p->llink!=NULL)
p=p->rlink;
head=p;
printf("NULLn");
}
void main()
{
int ch;

                                         9
clrscr();
printf(" Doubly linked list operationsn" );
printf("1.insert 2.delete 3.display 4.exit n");
head=(node*) malloc(sizeof( node));
tail=(node*) malloc(sizeof( node));
head->data=0;
head->llink= NULL;
tail->data=1000;
tail->rlink= NULL;
head->rlink= tail;
tail->llink= head;
do
{
printf("enter your choice :");
scanf("%d",& ch);
switch(ch)
{
case 1:
ins(head);
break;
case 2:
delete(head) ;
break;
case 3:
dis(head);
getch();
}
}
while(ch!=4) ;
free(head);
free(tail);
}




INPUT & OUTPUT:


                                               10
Doubly linked list operations
1.insert 2.delete 3.display 4.exit

enter your choice :1
enter the element into the list :1

enter your choice :1
enter the element into the list :2

enter your choice :3
1-> 2-> NULL

enter your choice :2
enter the deleted element :4
data not found

enter your choice :2
enter the deleted element :1

enter your choice :3
2-> NULL

enter your choice :4
<Exiting>




RESULT:

      Thus the program for program for implementation of doubly linked list has been
completed successfully and output verified.

Ex no – 2                POLYNOMIAL ADDITION

                                        11
AIM:
       To write a c program represent a polynomial as a linked list and write functions
for polynomial addition
.
ALGORITHM:
       Step1: Start the program.

       Step2: Include the required header files at the top of the program.

       Step3: Declare the needed variables and initialize them.

       Step4: Get the value of co – efficient and exponent value of two polynomial

               expressions

       Step5: Compare the exponent of two polynomial expressions.

       Step6: If the exponent values are same add the polynomial co – efficient.

       Step7: If the exponent values are different add the biggest exponent’s co –

               efficient value in to the result polynomial.

       Step8: Print the result polynomial expression.

       Step9: End of the program.




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

                                            12
typedef struct poly
{
int coeff;
int expo;
}p;
p p1[10],p2[10],p3[10];
void main()
{
int t1,t2,t3;
int read(p p1[10]);
int add(p p1[10],p p2[10],int t1,int t2,p p3[10]);
void print(p p2[10],int t2);
void printo(p pp[10],int t2);
t1=read(p1);
print(p1,t1);
t2=read(p2);
print(p2,t2);
t3=add(p1,p2,t1,t2,p3);
printo(p3,t3);
getch();
}
int read(p p[10])
{
int t1,i;
printf("nEnter the total no of terms in polynomial:");
scanf("%d",&t1);
printf("Enter the coefficient and exponent in descending order");
for(i=0;i<t1;i++)
scanf("%d%d",&p[i].coeff,&p[i].expo);
return(t1);
}
int add(p p1[10],p p2[10],int t1,int t2,p p3[10])
{
int i=0,j=0,k=0,t3;
while(i<t1&&j<t2)
{
if(p1[i].expo==p2[j].expo)
{
p3[k].coeff=p1[i].coeff+p2[j].coeff;
p3[k].expo=p1[i].expo;
i++;j++;k++;
}
else if(p1[i].expo>p2[j].expo)
{
p3[k].coeff=p1[i].coeff;
p3[k].expo=p1[i].expo;

                                           13
i++;k++;
}
else
{
p3[k].coeff=p2[j].coeff;
p3[k].expo=p2[j].expo;
j++;k++;
}
}
while(i<t1)
{
p3[k].coeff=p1[i].coeff;
p3[k].expo=p1[i].expo;
i++;k++;
}
while(j<t2)
{
p3[k].coeff=p2[j].coeff;
p3[k].expo=p2[j].expo;
j++;k++;
}
t3=k;
return(t3);
}
void print(p pp[10],int term)
{
int k;
printf("Printing the polynomial");
for(k=0;k<term-1;k++)
printf("%dx^%d+",pp[k].coeff,pp[k].expo);
printf("%dx^%d",pp[k].coeff,pp[k].expo);
}
void printo(p pp[10],int term)
{
int k;
printf("nAddition of polynomial");
for(k=0;k<term-1;k++)
printf("%dx^%d+",pp[k].coeff,pp[k].expo);
printf("%dx^%d",pp[k].coeff,pp[k].expo);
}




INPUT & OUTPUT:


                                        14
Enter the total no of terms in polynomial:3
Enter the coefficient and exponent in descending order3
3
2
2
1
0
Printing the polynomial3x^3+2x^2+1x^0

Enter the total no of terms in polynomial:3
Enter the coefficient and exponent in descending order4
2
3
1
5
0
Printing the polynomial4x^2+3x^1+5x^0

Addition of polynomial3x^3+6x^2+3x^1+6x^0




RESULT:

              Thus the program for program for polynomial addition has been
completed successfully and output verified.

Ex no – 3        IMPLEMENTATION OF STACK

                                              15
AIM:
       To write a c program to implement stack operations using array.

ALGORITHM:
       Step1: Start the program.

       Step2: Include the required header files at the top of the program.

       Step3: Declare the needed variables and initialize them.

       Step4: In push () operation, check whether the stack is full or not. If the stack is

                not full, insert the element into the stack by incrementing top value.

       Step5: In pop () operation, check whether the stack is empty or not. If the stack

                is not empty, delete the element from the stack by decrementing top

                value.

       Step6: In display () method, print the stack elements using for loop.

       Step7: In main () method, using switch case statement to invoke the methods

                according to the user choice entered.

       Step8: End of the program.




PROGRAM:
#include<stdio.h>

                                            16
#include<conio.h>
#define size 10
int stack[size],top=-1;
void push();
void pop();
void display();
void main()
{
int c;
clrscr();
printf("nn1.pushn2.popn3.displayn4.Exit");
do
{
printf("nnEnter your choice::");
scanf("%d",&c);
switch(c)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
printf("nnContents of stack ist");
display();
break;
default:
printf("nInvalid Choice");
exit(0);
}
}while(c<4);
getch();
}
void push()
{
int b;
if(top>size-1)
{
printf("nstack over flow");
return;
}
else
{
printf("nEnter the number to push into the stack:");
scanf("%d",&b);

                                            17
top++;
stack[top]=b;
return;
}
}
void pop()
{
int res;
if(top==0)
{
printf("nStack Underflow");
}
else
{
res=stack[top];
top--;
printf("nDeleted element is %d",res);
return;
}
}
void display()
{
int i;
if(top==-1)
{
printf("nStack Under flow");
return;
}
else
{
for(i=top;i>=0;i--)
printf("%d",stack[i]);
}
}




INPUT & OUTPUT:
1.push

                                         18
2.pop
3.display
4.Exit

Enter your choice::1
Enter the number to push into the stack:1

Enter your choice::1
Enter the number to push into the stack:2

Enter your choice::1
Enter the number to push into the stack:3

Enter your choice::3
Contents of stack is 3 2 1

Enter your choice::2
Deleted element is 3

Enter your choice::3
Contents of stack is 2 1

Enter your choice:: 4
<Exiting>




RESULT:

      Thus the program for program for implementation of stack using array has been
completed successfully and output verified.
Ex.No:4       INFIX TO POSTFIX CONVERSION
                                            19
AIM:
       Write a C program to Implement stack and use it to convert infix to postfix
expression


ALGORITHM:
       Step1: Start the program.

       Step2: Initialize the stack.

       Step3: Read the given infix expression into string called infix.

       Step4: If the character is an operand, place it on the output.

       Step5: If the character is an operator, push it on to the stack. if the stack operator

               has a higher or equal priority than input operator then pop that operator

               from the stack and place it onto the output.

       Step6: If the character is a left parenthesis, push it onto the stack.

       Step7: If the character is a right parenthesis, pop all operators from the stack till it

               encounters left parenthesis, discard both the parenthesis in the output.

       Step8: Display the postfix expression for the given infix expression.

       Step9: End the program.




PROGRAM:
#include<stdio.h>

                                             20
#include<conio.h>
#include<stdlib.h>
char inf[40],post[40];
int top=0,st[20];
void postfix();
void push(int);
char pop();
void main()
{
clrscr():
printf(“Enter the infix expression:”);
scanf(“%s”,&inf);
postfix();
getch();
}
void postfix()
{
int i,j=0;
for(i=0;inf[i]!=’0’;i++) {
switch(inf[i]) {
case ‘+’:
while(st[top>=1)
post[j++]=pop();
push(1);
break;
case ‘-’:
while(st[top>=1)
post[j++]=pop();
push(2);
break;
case ‘*’:
while(st[top>=3)
post[j++]=pop();
push(3);
break;
case ‘/’:
while(st[top>=3)
post[j++]=pop();
push(4);
break;
case ‘^’:
while(st[top>=4)
post[j++]=pop();
push(5);
break;
case ‘(’:

                                         21
push(0);
break;
case ‘)’:
while(st[top!=0)
post[j++]=pop();
top--;
break;
default: post[j++]=inf[i];
} }
while(top>0)
post[j++]=pop();
printf(“nPostfix expression is %s”,post);
}
void push(int ele) {
top++;
st[top]=ele;
}
char pop()
{
int e1;
char e;
e1=st[top];
top--;
switch(e1)
 {
case 1:
e=’+’;
break;
case 2:
e=’-’;
break;
case 3:
e=’*’;
break;
case 4:
e=’/’;
break;
case 5:
e=’^’;
break;
}
return(e);
}

INPUT & OUTPUT:
Enter the infix expression: a+b

                                             22
Postfix expression is ab+




RESULT:

      Thus the program for program for infix to postfix expression conversion has been
completed successfully and output verified.

Ex no – 5        IMPLEMENTATION OF QUEUE
                                         23
AIM:
       To write a c program to implement queue operations using array.

ALGORITHM:
       Step1: Start the program.

       Step2: Include the required header files at the top of the program.

       Step3: Declare the needed variables and initialize them.

       Step4: In insert () operation, check whether the queue is full or not. If the queue

               is not full, insert the element into the queue by incrementing rear value.

       Step5: In delete () operation, check whether the queue is empty or not. If the

               queue is not empty, delete the element from the queue by incrementing

               front value.

       Step6: In display () method, print the queue elements using for loop.

       Step7: In main () method, using switch case statement to invoke the methods

               according to the user choice entered.

       Step8: End of the program.




PROGRAM:
#include <stdio.h>

                                           24
#include<conio.h>
#define MAXSIZE 2
int q[MAXSIZE];
int front=-1,rear=-1,ch;
void main()
{
void insert();
int del();
void display();
clrscr();
do
{
printf("nMAIN MENU:1.Insert 2.Delete 3.Display 4.ExitnEnter ur choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
insert();
        break;
case 2: del();
        break;
        case 3:
        display();
        break;
        case 4:
        exit(0);
default: printf("Invalid Choice ... ");
}
} while(ch!=4);
}
void insert()
{
int num;
if(rear==(MAXSIZE-1))
        {
        printf("QUEUE FULL");
        return;
        }
else
        {
        printf("Enter the no:");
        scanf("%d",&num);
        rear=rear+1;
        q[rear]=num;
if(front==-1)
front++;

                                         25
}return;
}
int del()
{
 int num;
if(front==-1)
        {
        printf("QUEUE EMPTY");
        return 0;
        }
else
        {
        num=q[front];
        printf("nDeleted element is %d",q[front]);
        front++;
        }
        return(num);
        }
void display()
{
int i;
if(front==-1)
{
printf("Queue empty");
return;
}
else
{
printf("nQueue elements are:");
for(i=front;i<=rear;i++)
printf("%dt",q[i]);
}
}




INPUT & OUTPUT:

                                            26
MAIN MENU:1.Insert 2.Delete 3.Display 4.Exit
Enter ur choice:3
Queue empty


MAIN MENU:1.Insert 2.Delete 3.Display 4.Exit
Enter ur choice:1
Enter the no:1

MAIN MENU:1.Insert 2.Delete 3.Display 4.Exit
Enter ur choice:1
Enter the no:2

MAIN MENU:1.Insert 2.Delete 3.Display 4.Exit
Enter ur choice:1
QUEUE FULL

MAIN MENU:1.Insert 2.Delete 3.Display 4.Exit
Enter ur choice:2
Deleted element is 1

MAIN MENU:1.Insert 2.Delete 3.Display 4.Exit
Enter ur choice:2
Deleted element is 2

MAIN MENU:1.Insert 2.Delete 3.Display 4.Exit
Enter ur choice:3
Queue elements are:

MAIN MENU:1.Insert 2.Delete 3.Display 4.Exit
Enter ur choice:4
<Exiting>




RESULT:

      Thus the program for program for implementation of queue using array has been
completed successfully and output verified.

Ex no – 6       IMPLEMENTATION OF CIRCULAR

                                        27
QUEUE

AIM:
       To write a c program to implement circular queue using array.


ALGORITHM:
       Step1: Start the program.

       Step2: Include the required header files at the top of the program.

       Step3: Declare the needed variables and initialize them.

       Step4: In insert () operation, check whether the queue is full or not. If the queue

               is not full, check the front value if no element is there, insert the element

               into the queue in front position.

       Step5: In delete () operation, check whether the queue is empty or not. If the

               queue is not empty, delete the element from the queue by incrementing

               front value.

       Step6: In display () method, print the queue elements using for loop.

       Step7: In main () method, using switch case statement to invoke the methods

               according to the user choice entered.

       Step8: End of the program.




                                            28
PROGRAM:
#include<stdio.h>
#include<conio.h>
#define max 5
int q[max];
int front=-1;
int rear=-1;
void main()
{
int ch;
clrscr();
while(1)
{
printf("enter your choice");
scanf("%d",&ch);
switch(ch)
{
case 1:
insert();
break;
case 2:
del();
break;
case 3:
display();
break;
case 4:
exit(1);
default:
printf("in wrong choice");
}
}
}
insert()
{
int item;
if((front==0&&rear==max-1)||(front==rear+1))
{
printf("n queue overflow");
return;
}
if (front==-1)
{
front=0;
rear=0;
}

                                        29
else
if(rear==max-1)
rear=0;
else
rear=rear+1;
printf("enter the element");
scanf("%d",&item);
q[rear]=item;
}
del()
{
if(front==-1)

{
printf("queue underflown");
return;
}
printf("element deleted from queue is %d:n",q[front]);
if(front==rear)
{
rear=-1;
front=-1;
}
else
if(front==max-1)
front=0;
else
front=front+1;
}
display()
{
int fpos=front,rpos=rear;
if(front==-1)
{
printf("queue is emptyn");
return;
}
printf("queue elements:n");
if(fpos<=rpos)
while(fpos<=rpos)
{
printf("%dn",q[fpos]);
fpos++;
}
else
{

                                           30
while(fpos<=max-1)
{
printf("%dn",q[fpos]);
fpos++;
}
fpos=0;
while(fpos<=rpos)
{
printf("%d",q[fpos]);
fpos++;
}
}
printf("n");
}




                          31
INPUT & OUTPUT:

1.insert 2.delete 3.display 4.quit
enter your choice1
enter the element1

1.insert 2.delete 3.display 4.quit
enter your choice1
enter the element2

1.insert 2.delete 3.display 4.quit
enter your choice3
queue elements:
1
2

1.insert 2.delete 3.display 4.quit
enter your choice2
element deleted from queue is 1:

1.insert 2.delete 3.display 4.quit
enter your choice3
queue elements:
2

1.insert 2.delete 3.display 4.quit
enter your choice4
<Exiting>




RESULT:
       Thus the program for implementation of circular queue has been completed
successfully and output verified.

                                      32
Ex no – 7         IMPLEMENTATION OF EXPRESSION
                          TREE

AIM:
       To write a c program to implement an expression tree. Produce its pre-order, in-
order, and post order traversals.


ALGORITHM:
       Step1: Start the program.

       Step2: Include the required header files at the top of the program.

       Step3: Declare the function inorder(), postorder(), preorder().

       Step4: Read the input in the form of postfix expression.

       Step5: In inorder () function, traversal will be from left child-->root-->right

                child.

       Step6: In preorder () function, traversal will be from root-->left child--> right

                child.

       Step7: In postorder () function, traversal will be from left child--> right

                child-->root.

       Step8: In main () method, using switch case statement to invoke the methods

                according to the user choice entered.

       Step9: End of the program.




                                            33
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define size 20
typedef struct node
{
char data;
struct node *left;
struct node *right;
}btree;
btree *stack[size];
int top;
void main()
{
btree *root;
char exp[80];
btree *create(char exp[80]);
void inorder(btree *root);
void preorder(btree *root);
void postorder(btree *root);
clrscr();
printf(“nEnter the postfix expression:”);
scanf(“%s”,&exp);
top=-1;
root=create(exp);
printf(“nInorder traversal:”);
inorder(root);
printf(“nPreorder traversal:”);
preorder(root);
printf(“nPostorder traversal:”);
postorder(root);
getch();
}
btree *create(char exp[])
{
btree *temp;
int pos;
char ch;
void push(btree *);
btree *pop();
pos=0;
ch=exp[pos];
while(ch!=’0’)
{
temp=(btree *)malloc(sizeof(btree));

                                             34
temp->left=temp->right=NULL;
temp->data=ch;
if(isalpha(ch))
push(temp);
else if(ch==’+’||ch==’-‘||ch==’*’||ch==’/’)
 {
temp->right=pop();
temp->left=pop();
push(temp);
  }
else
printf(“nInvalid character in expression”);
pos++;
ch=exp[pos];
}
temp=pop();
return(temp);
 }
void push(btree *node)
 {
if(top+1>=size)
printf(“Error:Stack is full”);
top++;
stack[top]=node;
}
btree *pop()
{
btree *node;
if(top==-1)
printf(“Error:Stack empty”);
node=stack[top];
top--;
return(node);
}
void inorder(btree *root)
{
btree *temp;
temp=root;
if(temp!=NULL)
{
inorder(temp->left);
printf(“%c”,temp->data);
inorder(temp->right);
}
}
void preorder(btree *root) {

                                               35
btree *temp;
temp=root;
if(temp!=NULL)
{
printf(“%c”,temp->data);
preorder(temp->left);
preorder(temp->right);
}
}
void postorder(btree *root)
{
btree *temp;
temp=root;
if(temp!=NULL) {
postorder(temp->left);
postorder(temp->right);
printf(“%c”,temp->data);
}
}




                              36
INPUT & OUTPUT:

Enter the postfix expression:ab+cd-*

Inorder traversal:a+b*c-d
Preorder traversal:*+ab-cd
Postorder traversal:ab+cd-*




RESULT:
       Thus the program for implementation of expression tree and its traversal order has
been completed successfully and output verified.

                                           37
Ex no – 8        IMPLEMENTATION OF BINARY
                      SEARCH TREE

AIM:
       To write a c program to implement binary search tree.
ALGORITHM:

       Step1: Start the program.

       Step2: Include the required header files at the top of the program.

       Step3: Declare the function add(),search(), findmin(),findmax() and display().

       Step4: In main () method, using switch case statement to invoke the methods

               according to the user choice entered.

       Step5: In add () function, get the number from user and insert it into tree.

       Step6: In search () function, the number given for search will be traversed and

               result of the searching will be displayed.

       Step7: In findmin () function, display the minimum element in the tree

       Step8: In findmax () function, display the maximum element in the tree

       Step8: In display() function, the binary search tree will be displayed.

       Step9: End of the program.




                                           38
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *left, *right;
}*nptr;
nptr root,t,p,q;
void add();
void search();
void findmin();
void findmax();
void disp(nptr,int,int,int);
void main()
{
int ch;
root=NULL;
while(1)
{
printf(“1.Create 2.Search 3.Display 4.Findmin 5.Findmax 6.ExitnEnter ur choice:”);
scanf(“%d”,&ch);
switch(ch)
{
case 1:
add();
break;
case 2:
search();
break;
case 3:
clrscr();
disp(root,40,7,16);
break;
case 4:
findmin();
break;
case 5:
findmax();
break;
case 6:
exit(0);
}
}
}

                                          39
void add()
{
int x;
t=(nptr)malloc(sizeof(struct node));
printf(“nEnter data:”);
scanf(“%d”,&x);
t->data=x;
t->left=NULL;
t->right=NULL;
if (root==NULL)
root=t;
else
{
p=q=root;
while(q!=NULL&&x!=p->data)
{
p=q;
if(x<p->data)
q=p->left;
else
q=p->right;
}
if(x==p->data)
printf(“%d is duplicate no n”,x);
else if(x<p->data)
p->left=t;
else
p->right=t;
}
}
void search()
{
int x;
printf(“Enter the element to search:”);
scanf(“%d”,&x);
p=q=root;
while(q!=NULL&&x!=p->data)
{
p=q;
if(x<p->data)
q=p->left;
else
q=p->right;
}
if(x==p->data)
printf(“Element is present”);

                                          40
else
printf(“Element not present”);
}
void disp(nptr root,int col,int row,int wid)
{
gotoxy(col,row);
if(root!=NULL)
{
printf(“%d”,root->data);
disp(root->left,col-wid,row+2,wid/2);
disp(root->right,col+wid,row+2,wid/2);
}
}
void findmax()
{
t=root;
while(t->right!=NULL)
t=t->right;
printf(Maximum value in BST is %d”,t->data);
}
void findmin()
{
t=root;
while(t->left!=NULL)
t=t->left;
printf(Minimum value in BST is %d”,t->data);
}




                                        41
INPUT & OUTPUT:
1.Create 2.Search 3.Display 4.Findmin 5.Findmax 6.Exit
Enter ur choice:1
Enter data:10
1.Create 2.Search 3.Display 4.Findmin 5.Findmax 6.Exit
Enter ur choice:1
Enter data:9
1.Create 2.Search 3.Display 4.Findmin 5.Findmax 6.Exit
Enter ur choice:1
Enter data:8
1.Create 2.Search 3.Display 4.Findmin 5.Findmax 6.Exit
Enter ur choice:1
Enter data:11
1.Create 2.Search 3.Display 4.Findmin 5.Findmax 6.Exit
Enter ur choice:1
Enter data:12
1.Create 2.Search 3.Display 4.Findmin 5.Findmax 6.Exit
Enter ur choice:3
                        10

              9                     11

         8                               12

1.Create 2.Search 3.Display 4.Findmin 5.Findmax 6.Exit
Enter ur choice:2
Enter the element to search:8
Element is present
1.Create 2.Search 3.Display 4.Findmin 5.Findmax 6.Exit
Enter ur choice:2
Enter the element to search:7
Element not present
1.Create 2.Search 3.Display 4.Findmin 5.Findmax 6.Exit
Enter ur choice:4
Minimum value in BST is 8
1.Create 2.Search 3.Display 4.Findmin 5.Findmax 6.Exit
Enter ur choice:5
Maximum value in BST is 12
1.Create 2.Search 3.Display 4.Findmin 5.Findmax 6.Exit
Enter ur choice:6 <Exiting…..>


RESULT:
       Thus the program for implementation of binary search tree has been completed
successfully and output verified.

                                              42
Ex no – 9         IMPLEMENTATION OF PRIORITY
                       QUEUE USING HEAPS

AIM:
       To write a c program to implement priority queue using heap.

ALGORITHM:

       Step1: Start the program.

       Step2: Include the required header files at the top of the program.

       Step3: Declare the needed variables and initialize them.

       Step4: By defining the priority queue, we can perform operations on heap.

       Step5: Insert an item arbitrarily at anywhere in the priority queue.

       Step6: Delete an item that has highest priority i.e. maximum value from the

               priority queue. This is called max heap.

       Step7: Delete an item that has lowest priority i.e. minimum value from the

               priority queue. This is called min heap.

       Step8: Print the contents of heap using for loop.

       Step9: End of the program.




                                           43
PROGRAM:
#include<stdio.h>
#include<conio.h>
#define size 5
void main(void)
{
int rear,front,que[size],choice;
int qfull(int rear),qempty(int rear,int front);
int insert(int que[size],int rear,int front);
int delet(int que[size],int front);
void display(int que[size],int rear,int front);
clrscr();
front=0;
rear=-1;
do
{
printf("nMainmenu1:insert 2:delete 3:display 4.Exitnenter ur choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1:if(qfull(rear))
printf("nqueue is full");
else
rear=insert(que,rear,front);
break;
case 2:
if(qempty(rear,front))
printf("ncannot delete element");
else
front=delet(que,front);
break;
case 3:
if(qempty(rear,front))
printf("nqueue is empty");
else
display(que,rear,front);
break;
case 4:
exit(0);
default:
printf("nwrong choice");
break;
}
}while(choice!=4);
getch();
}

                                            44
int insert(int que[size],int rear,int front)
{
int item,j;
printf("nenter the element : ");
scanf("%d",&item);
if(front==-1)
front++;
j=rear;
while(j>=0&&item<que[j])
{que[j+1]=que[j];
j--;
}
que[j+1]=item;
rear=rear+1;
return rear;
}
int qfull(int rear)
{
if(rear==size-1)
return 1;
else
return 0;
}
int delet(int que[size],int front)
{
int item;
item=que[front];
printf("nthe item deleted is %d",item);
front++;
return front;
}
qempty(int rear,int front)
{
if((front==-1)||(front>rear))
return 1;
else
return 0;
}
void display(int que[size],int rear,int front)
{
int i;
printf("nthe queue is :");
for(i=front;i<=rear;i++)
printf(" %d",que[i]);
}



                                                 45
INPUT & OUTPUT:

Mainmenu1:insert 2:delete 3:display 4.Exit
enter ur choice: 1
enter the element : 1

Mainmenu1:insert 2:delete 3:display 4.Exit
enter ur choice: 1
enter the element : 2

Mainmenu1:insert 2:delete 3:display 4.Exit
enter ur choice: 1
enter the element : 3

Mainmenu1:insert 2:delete 3:display 4.Exit
enter ur choice: 3
the queue is : 1 2 3

Mainmenu1:insert 2:delete 3:display 4.Exit
enter ur choice: 2
the item deleted is 1

Mainmenu1:insert 2:delete 3:display 4.Exit
enter ur choice: 2
the item deleted is 2

Mainmenu1:insert 2:delete 3:display 4.Exit
enter ur choice: 2
the item deleted is 3

Mainmenu1:insert 2:delete 3:display 4.Exit
enter ur choice: 2
cannot delete element

Mainmenu1:insert 2:delete 3:display 4.Exit
enter ur choice: 3
queue is empty

Mainmenu1:insert 2:delete 3:display 4.Exit
enter ur choice: 4<Exiting>

RESULT:

      Thus the program for implementation of priority queue using heap has been
completed successfully and output verified.


                                             46
Ex no – 10    IMPLEMENTATION OF HASHING
                    TECHINQUE


AIM:
       To write a c program to implement hashing by linear probing.

ALGORITHM:

       Step1: Start the program.

       Step2: Include the required header files at the top of the program.

       Step3: Declare and initialize needed variables.

       Step4: Get the size of the hash table from the user and makes the indices

               sequentially based on size.

       Step5: Then get the integer number from the user . And compute the hash

               function for that number using the given formula.

                     Hash function= (int) e % size of the hash table

       Step6: Finally, store the number in corresponding location in the hash table.

       Step7: Check whether the hash table is empty or full during insertion and

               deletion function.

       Step8: Print the contents of hash table whenever the user needs to view.

       Step9: End of the program.




                                             47
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define MAX 10
void main()
{
int a[MAX],num,key,i;
char ans;
int create(int);
void linear_prob(int [],int,int),display(int []);
clrscr();
printf("nCollision handling by linear probing");
for(i=0;i<MAX;i++)
a[i]=-1;
do
{
printf("nEnter the number");
scanf("%d",&num);
key=create(num);
linear_prob(a,key,num);
printf("ndo you wish to continue? (y/n)");
ans=getche();
}while(ans=='y');
display(a);
getch();
}
int create(int num)
{
int key;
key=num%10;
return key;
}
void linear_prob(int a[MAX],int key,int num)
{
int flag,i,count=0;
void display(int a[]);
flag=0;
if(a[key]==-1)
a[key]=num;
else
{
i=0;
while(i<MAX)
{
if(a[i]!=-1)

                                            48
count++;
i++;
}
if(count==MAX)
{
printf("nhash table is full");
display(a);
getch();
exit(1);
}
for(i=key+1;i<MAX;i++)
if(a[i]==-1)
{
a[i]=num;
flag=1;
break;
}
for(i=0;i<key&&flag==0;i++)
if(a[i]==-1)
{
a[i]=num;
flag=1;
break;
}}}
void display(int a[MAX])
{
int i;
printf("nthe hash table");
for(i=0;i<MAX;i++)
printf("n%dt%d",i,a[i]);
}




                                  49
INPUT & OUTPUT:

Collision handling by linear probing
Enter the number33
do you wish to continue? (y/n)y
Enter the number83
do you wish to continue? (y/n)y
Enter the number35
do you wish to continue? (y/n)y
Enter the number42
do you wish to continue? (y/n)y
Enter the number74
do you wish to continue? (y/n)n
the hash table
0     -1
1     -1
2     42
3     33
4     83
5     35
6     74
7     -1
8     -1
9     -1




RESULT:

      Thus the program for implementation of hashing by linear probing has been
completed successfully and output verified.

                                       50
Ex no – 11        IMPLEMENTATION OF TOPOLOGICAL
                           SORTING

AIM:
       To write a c program to implement topological sorting.


ALGORITHM:
       Step1: Start the program.

       Step2: Include the required header files at the top of the program.

       Step3: Declare the function push(), pop(), ts().

       Step4: In push () function, check whether the stack is full or not. If the stack is

                not full, insert the vertex into the stack by incrementing top value.

       Step5: In pop () operation, check whether the stack is empty or not. If the stack

                is not empty, get the vertex from the stack by decrementing top

                value.

       Step6: In ts () function, traversal order for the given graph is found.

       Step7: In main () method, get the adjacency matrix for given number of vertices

               from user and call the required function.

       Step8: End of the program.




                                            51
PROGRAM:
#include<stdio.h>
#include<conio.h>
#define max 30
int stack[max],top=-1;
int push(int v);
int pop(int *v);
int ts(int mat[max][max],int n,int order[max]);
void main()
{
int i,j,n,mat[max][max],order[max],succ;
clrscr();
printf("nenter the no. of vertices : ");
scanf("%d",&n);
printf("nenter adjacency matrix :n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&mat[i][j]);
succ=ts(mat,n,order);
if(succ==1)
{printf("nnthe directed graph is acyclic");
printf("nnthe topological sorted order isn");
for(i=0;i<n;i++)
printf("%dt",order[i]+1);
}
else
printf("nthe directed graph is not acyclic");
getch();
}
int push(int v)
{
if(top==max-1)
return 0;
else
stack[++top]=v;
return -1;
}
int pop(int *v)
{
if(top==-1)
return 0;
else
*v=stack[top--];
return -1;
}
int ts(int mat[max][max],int n,int order[max])

                                             52
{
int indegree[max],v,i,k,m;
for(i=0;i<n;i++)
{
indegree[i]=0;
for(k=0;k<n;k++)
if(mat[k][i]==1)
indegree[i]++;
if(indegree[i]==0)
push(i);
}
m=0;
while(pop(&v))
{
order[m++]=v;
for(k=0;k<n;k++)
if(mat[v][k]==1&&indegree[k]>0)
{indegree[k]--;
if(indegree[k]==0)
push(k);
}
}
return (i==n);
}




                                  53
INPUT & OUTPUT:
Enter the no. of vertices : 7
Enter adjacency matrix:
0111000
0001100
0000010
0010011
0001001
0000000
0000010

The directed graph is acyclic

The topological sorted order is

1       2       5       4       7   3      6




RESULT:
        Thus the program for implementation of topological sorting has been completed
successfully and output verified.


                                         54
Ex no – 12       IMPLEMENTATION OF DIJKSTRA’S
                       ALGORITHM
AIM:
       To write a c program to implement dijkstra’s algorithm.

ALGORITHM:

       Step1: Start the program.

       Step2: Include the required header files at the top of the program.

       Step3: Get the number of vertices from the user and get cost for each vertex.

       Step4: The general algorithm for this process is as follows,

             o select a starting node
             o build the initial fringe from nodes connected to the starting node
             o while we are not at the destination node do
                      •   choose the fringe node with the shortest path to the starting node
                      •   add that node and its edge to the tree
                      •   update the fringe by:
                              adding nodes to the fringe connected to the new node
                              for each node in the fringe do
                                   update its edge one connected to the tree on the
                                   shortest path to the starting node
                              end for
             o end while

       Step5: Print the shortest path.

       Step6: End of the program.




                                              55
PROGRAM:
#include<stdio.h>
#include<conio.h>
#define INFINITY 1000
int a[10][10],b[10][10];
int i,j,k,n;
void input();
void initialize();
void spath();
void display();
void input()
{
printf("nt *** DIJKSTRA’S ALGORITHM ***");
printf("n enter the no of vertices:");
scanf("%d",&n);
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
if(i!=j)
{
printf("cost between %d to %d",i,j);
scanf("%d",&a[i][j]);
}
}
}
void initialize()
{
for(i=1;i<=n;i++)
a[i][j]=0;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
b[i][j]=a[i][j];
if(!a[i][j] && (i!=j))
{
b[i][j]=INFINITY;
}
}
}
void spath()
{
for(k=1;k<=n;k++)
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if((b[i][k] && b[k][j]) && (b[i][k]+b[k][j]<b[i][j]))
{

                                            56
b[i][j]=b[i][k]+b[k][j];
}
}
void display()
{
i=1;
if(i<n)
{
for(j=2;j<=n;j++)
printf("Minimum cost FROM source vertex 1 TO %d is : %dn",j,b[i][j]);
}
}
void main()
{
clrscr();
input();
initialize();
spath();
display();
getch();
}




                                         57
INPUT & OUTPUT:

        *** DIJKSTRA’S ALGORITHM ***
enter the no of vertices: 5




cost between1—2: 2
cost between1—3: 1
cost between1—4: 0
cost between1—5: 0
cost between2—1: 2
cost between2—3: 5
cost between2—4: 4
cost between2—5: 0
cost between3—1: 1
cost between3—2: 5
cost between3—4: 3
cost between3—5: 2
cost between4—1: 0
cost between4—2: 4
cost between4—3: 3
cost between4—5: 6
cost between5—1: 0
cost between5—2: 0
cost between5—3: 2
cost between5—4: 6
minimum cost FROM 1 TO 2 is : 2
minimum cost FROM 1 TO 3 is : 1
minimum cost FROM 1 TO 4 is : 4
minimum cost FROM 1 TO 5 is : 3

RESULT:

       Thus the program for implementation of dijkstra’s algorithm has been completed
successfully and output verified.

                                         58
Ex no – 13(A)         IMPLEMENTATION OF PRIM’S
                           ALGORITHM
AIM:
       To write a c program to implement prim’s algorithm.

ALGORITHM:

       Step1: Start the program.

       Step2: Include the required header files at the top of the program.

       Step3: Get the number of nodes from the user and get weight for each vertex.

       Step4: The general algorithm for this process is as follows,

          o select a starting node.

          o build the initial fringe from nodes connected to the starting node

          o while there are nodes left do

                     choose the edge to the fringe of the smallest weight

                     add the associated node to the tree

                     update the fringe by:

                         •   adding nodes to the fringe connected to the new node

                         •   updating the edges to the fringe so that they are the smallest


          o end while

       Step5: Print the minimal spanning tree.

       Step6: End of the program.




                                              59
PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
int lowcost[20],min;
int n,noe,i,j,k,v,closest[20],u,cost[50][50];
clrscr();
printf("ENTER THE NO OF NODES:");
scanf("%d",&n);
printf("nENTER NO OF EDGES:");
scanf("%d",&noe);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
cost[i][j]=1000;
}
}
for(i=1;i<=noe;i++)
{
printf("ENTER THE EDGE: ");
scanf("%d%d",&u,&v);
printf("ENTER COST OF EDGE:");
scanf("%d",&cost[u][v]);
cost[v][u]=cost[u][v];
}
printf("nThe output of minimum spanning tree will be...n");
for(i=2;i<=n;i++)
{
lowcost[i]=cost[1][i];
closest[i]=1;
}
for(i=2;i<=n;i++)
{
min=lowcost[2];
k=2;
for(j=3;j<=n;j++)
{
if(lowcost[j]<min)
{
min=lowcost[j];
k=j;
}

                                           60
}
printf("%d ->%d:cost %dn",k,closest[k],lowcost[k]);
lowcost[k]=2000;
for(j=2;j<=n;j++)
if((cost[k][j]<lowcost[j]) && (lowcost[j]<2000))
{
lowcost[j]=cost[k][j];
closest[j]=k;
}
}
getch();
}




                                          61
INPUT & OUTPUT:

ENTER THE NO OF NODES:4

ENTER NO OF EDGES:5
ENTER THE EDGE: 1
2
ENTER COST OF EDGE:9
ENTER THE EDGE: 1
3
ENTER COST OF EDGE:3
ENTER THE EDGE: 1
4
ENTER COST OF EDGE:2
ENTER THE EDGE: 2
4
ENTER COST OF EDGE:1
ENTER THE EDGE: 3
4
ENTER COST OF EDGE:6

The output of minimum spanning tree will be...
4 ->1:cost 2
2 ->4:cost 1
3 ->1:cost 3




RESULT:

       Thus the program for implementation of prim’s algorithm has been completed
successfully and output verified.

                                          62
Ex no – 13(B)     IMPLEMENTATION OF KRUSKAL’S
                        ALGORITHM
AIM:
       To write a c program to implement kruskal’s algorithm.

ALGORITHM:

       Step1: Start the program.

       Step2: Include the required header files at the top of the program.

       Step3: Get the number of nodes from the user and get weight for each node.

       Step4: Sort the edges in nondecreasing order by weight and initialize partition

                structure for finding the edges to be included in spanning tree.

       Step5: Print the minimum spanning tree.
       Step6: End of the program.




                                            63
PROGRAM:
#include<stdio.h>
#include<conio.h>
typedef struct edge
{
int node1,node2,wt;
}edge;
void sortedge(edge a[],int n)
{
int i,j;
edge temp;
for(i=0;i<n;i++)
for(j=i+1;j<n;++j)
if(a[i].wt>a[j].wt)
{
temp=a[i];a[i]=a[j];a[j]=temp;
}
}
int check(int p[],int i,int j)
{
int v1,v2;
v1=i;
v2=j;
while(p[i]>-1)
i=p[i];
while(p[j]>-1)
j=p[j];
if(i!=j)
{
p[j]=i;
printf("%d->%dn",v1,v2);
return 1;
}
return 0;
}
void main()
{
edge e[100];
int r[100],n,i,j,k=1,m,cost=0;
clrscr();
printf("Kruskal algorithmn");
printf("Enter the no of nodes:");
scanf("%d",&n);
for(i=0;i<n;i++)

                                    64
r[i]=-1;
i=0;
printf("nEnter no of edges:");
scanf("%d",&m);
for(i=0;i<m;i++)
{
printf("nENter the edge and cost of the edge:");
scanf("%d%d%d",&e[i].node1,&e[i].node2,&e[i].wt);
}
sortedge(e,m);
printf("nEdges of the MSTn");
i=0;
while(k<n)
{
if(check(r,e[i].node1,e[i].node2))
{
k++;
cost=cost+e[i].wt;
i++;
}
}
printf("Minimum cost:%d",cost);
getch();
}




                                       65
INPUT & OUTPUT:

Kruskal algorithm
Enter the no of nodes:4

Enter no of edges:4

Enter the edge and cost of the edge:1
2
1

Enter the edge and cost of the edge:1
3
3

Enter the edge and cost of the edge:2
3
2

Enter the edge and cost of the edge:2
4
1

Edges of the MST
1->2
2->4
2->3
Minimum cost:4




RESULT:



                                        66
Thus the program for implementation of kruskal’s algorithm has been completed
successfully and output verified.

Ex no – 14       IMPLEMENTATION OF BACKTRACKING
                          ALGORITHM

AIM:
       To write a c program to implement backtracking algorithm for Knapsack problem.


ALGORITHM:
       Step1: Start the program.

       Step2: Include the required header files at the top of the program.

       Step3: Declare the function knap(), bound().

       Step4: Get the input number of items and capacity of knapsack from user.

       Step5: Get the weight and profit for each item from user.

       Step6: In knap () function, the maximum capacity and profit are found

       Step7: In bound () function, the maximum capacity for inserting the item is

               checked.

       Step8: In main () method, the values of knapsack are printed in descending

               order.

       Step9: End of the program.




                                           67
PROGRAM:
#include<stdio.h>
#include<conio.h>
int n,m,i,j,x[10],y[10];
float w[10],t,t1,t2,p[10],c1[10],b,c,fp=-1.0,fw;
void knap(int,float,float);
float bound(float,float,int);
void main()
{
clrscr();
printf("nenter the no. of items : ");
scanf("%d",&n);
printf("nenter the maximum capacity of knapsack : ");
scanf("%d",&m);
for(i=1;i<=n;i++)
{
printf("nnenter the weight & profit : n");
scanf("%f%f",&w[i],&p[i]);
}
for(i=1;i<=n;i++)
{
for(j=i+1;j<=n;j++)
{
if(c1[i]>=c1[j])
t1=w[i];
w[i]=w[j];
w[j]=t1;
t2=p[i];
p[i]=p[j];
p[j]=t2;
t=c1[i];
c1[i]=c1[j];
c1[j]=t;
} }
printf("nnweightttprofitn");
for(i=1;i<=n;i++)
{
printf("n%ft%fn",w[i],p[i]);
knap(1,0,0);
printf("nnthe selected objects: ");
for(i=1;i<=n;i++)
{
printf("%d",x[i]);

                                           68
}
printf(“nFinal Weight=%0.2f”,fw);
printf(“nFinal Profit=%0.2f”,fp);
getch();
}
void knap(int k,float cp,float cw)
{
if(cw+w[k]<=m)
{
y[k]=1;
if(k<n)
knap(k+1,cp+p[k],cw+w[k]);
if((cp+p[k]>fp)&&(k==n))
{
fp=cp+p[k];
fw=cw+w[k];
for(j=1;j<=n;j++)
x[j]=y[j];
}
if(bound(cp,cw,k)>=fp)
{
y[k]=0;
if(k<n)
knap(k+1,cp,cw);
if((cp>fp)&&(k==n))
{
fp=cp;
fw=cw;
for(j=1;j<=n;j++)
x[j]=y[j];
}}}}
float bound(float cp,float cw,int k)
{
float b=cp,c=cw;
for(i=k+1;i<=n;i++)
{
c=c+w[i];
if(c<m)
b=b+p[i];
else
return(b+(1-(c-m))/w[i]*p[i]);
}
return b;
}




                                       69
INPUT & OUTPUT:
Enter the no. of items : 5
Enter the maximum capacity of knapsack : 20
Enter the weight & profit ; 3 12
Enter the weight & profit ; 2 4
Enter the weight & profit ; 4 8
Enter the weight & profit ; 5 10
Enter the weight & profit ; 4 12

Weight        profit
4.000000      12.000000
5.000000      10.000000
4.000000      8.0000000
2.000000      4.0000000
3.000000      12.000000

The selected objects are: 11111

Final Weight=18.00
Final Profit=46.00




RESULT:

                                        70
Thus the program for implementation of backtracking algorithm for knapsack
problem has been completed successfully and output verified.


Ex no – 15        IMPLEMENTATION OF BRANCH AND
                      BOUND ALGORITHM

AIM:
       To write a c program to implement branch and bound algorithm for travelling

salesman problem.

ALGORITHM:

       Step1: Start the program.

       Step2: Include the required header files at the top of the program.

       Step3: Declare the function tsp(), display().

       Step4: In main() method, get the number of cities and distance for each city

               from user.

       Step5: In tsp() function, finds the minimum distance from source.

       Step6: In display() function, minimum cost and path is displayed.

       Step7: End of the program.




                                           71
PROGRAM:
#include<stdio.h>
#include<conio.h>
#define max 10
typedef struct
{
int nodes[max];
int vertex;int min;
}path;
path tsp(int src,path list,int ele[][max],int mcities)
{
int i,j;
path nlist,npath,nmin;
if(list.vertex==0)
{
nmin.min=ele[src][1];
nmin.nodes[mcities-1]=src;
nmin.vertex=mcities;
return nmin;
}
for(i=0;i<list.vertex;i++)
{
nlist.vertex=0;
for(j=0;j<list.vertex;j++)
if(i!=j)
nlist.nodes[nlist.vertex++]=list.nodes[j];
npath=tsp(list.nodes[i],nlist,ele,mcities);
npath.min=ele[src][list.nodes[i]]+npath.min;
npath.nodes[mcities-list.vertex-1]=src;
if(i==0)
nmin=npath;
else
if(npath.min<nmin.min)
nmin=npath;
}
return nmin;
}
void display(path path1)
{
int i;
printf("nnthe minimum cost is %dn",path1.min);
printf("nthe path is....n");

                                              72
for(i=0;i<path1.vertex;i++)
printf("%d--",path1.nodes[i]);
printf("%d",path1.nodes[0]);
}
void main()
{
int i,j,ele[max][max],mcities;
path graph,path1;
clrscr();
printf("nenter number of cities : ");
scanf("%d",&mcities);
if(mcities==0)
{
printf("error : there is no city for proceeding the TSP");
}
else
{
for(i=1;i<=mcities;i++)
{
for(j=1;j<=mcities;j++)
if(i==j)
ele[i][i]=0;
else
{
printf("enter distance from city %d to %d [if no path put 999]: ",i,j);
scanf("%d",&ele[i][j]);
}
if(i>1)
graph.nodes[i-2]=i;
}
graph.vertex=mcities-1;
path1=tsp(1,graph,ele,mcities);
display(path1);
}
getch();
}




                                             73
INPUT & OUTPUT:

Enter number of cities : 4
Enter distance from city 1 to 2 [if no path put 999]: 1
Enter distance from city 1 to 3 [if no path put 999]: 999
Enter distance from city 1 to 4 [if no path put 999]: 999
Enter distance from city 2 to 1 [if no path put 999]: 999
Enter distance from city 2 to 3 [if no path put 999]: 5
Enter distance from city 2 to 4 [if no path put 999]: 1
Enter distance from city 3 to 1 [if no path put 999]: 1
Enter distance from city 3 to 2 [if no path put 999]: 999
Enter distance from city 3 to 4 [if no path put 999]: 3
Enter distance from city 4 to 1 [if no path put 999]: 4
Enter distance from city 4 to 2 [if no path put 999]: 999
Enter distance from city 4 to 3 [if no path put 999]: 1

The minimum cost is 4

The path is…..
1---2---4---3---1




RESULT:

                                            74
Thus the program for implementation of branch and bound algorithm for
travelling salesman problem has been completed successfully and output verified.


Ex no –16         IMPLEMENTATION OF RANDOMIZED
                         ALGORITHM

AIM:
       To write a c program to implement randomized algorithm- to find repeated
elements in the array.


ALGORITHM:
       Step1: Start the program.

       Step2: Include the required header files at the top of the program.

       Step3: Declare the function repetition().

       Step4: In main () method, used to print the repeated elements in the given array.

       Step5: Repetition () function, checks whether the declared array has repeated

                elements.

       Step6: End of the program.




                                           75
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<time.h>
int main(void)
{
int a[10]={10,20,30,40,11,12,13,10,30,30};
int n=10;
void repetition(int a[],int n);
clrscr();
printf("ntRANDOMIZED ALGORITHM - TO FIND REPEATED ELEMENTSn");
repetition(a,n);
getch();
return 0;
}
void repetition(int a[],int n)
{
int i,j,count;
time_t t;
srand((unsigned)time(&t));
count=1;
while(count<=100)
{
i=rand()%(n+1);
j=rand()%(n+1);
if((i!=j)&&(a[i]==a[j]))
printf("nthe repeated element is present at index %d",i);
count++;
}
}




                                76
INPUT & OUTPUT:

RANDOMIZED ALGORITHM – TO FIND REPEATED ELEMENTS
The repeated element is present at index 9
The repeated element is present at index 9
The repeated element is present at index 2
The repeated element is present at index 0
The repeated element is present at index 0
The repeated element is present at index 7
The repeated element is present at index 7
The repeated element is present at index 9
The repeated element is present at index 7
The repeated element is present at index 9




RESULT:
                                             77
Thus the program for implementation of randomized algorithm to find repeated
elements in the array has been completed successfully and output verified.




                                           78

Mais conteúdo relacionado

Mais procurados (20)

Stack using Linked List
Stack using Linked ListStack using Linked List
Stack using Linked List
 
Circular queue
Circular queueCircular queue
Circular queue
 
week-16x
week-16xweek-16x
week-16x
 
C++ programs
C++ programsC++ programs
C++ programs
 
Function basics
Function basicsFunction basics
Function basics
 
Cquestions
Cquestions Cquestions
Cquestions
 
Array list
Array listArray list
Array list
 
week-18x
week-18xweek-18x
week-18x
 
week-11x
week-11xweek-11x
week-11x
 
week-10x
week-10xweek-10x
week-10x
 
Pratik Bakane C++
Pratik Bakane C++Pratik Bakane C++
Pratik Bakane C++
 
week-15x
week-15xweek-15x
week-15x
 
Pratik Bakane C++
Pratik Bakane C++Pratik Bakane C++
Pratik Bakane C++
 
Pratik Bakane C++
Pratik Bakane C++Pratik Bakane C++
Pratik Bakane C++
 
week-1x
week-1xweek-1x
week-1x
 
week-21x
week-21xweek-21x
week-21x
 
week-6x
week-6xweek-6x
week-6x
 
Stl algorithm-Basic types
Stl algorithm-Basic typesStl algorithm-Basic types
Stl algorithm-Basic types
 
StackArray stack3
StackArray stack3StackArray stack3
StackArray stack3
 
Pratik Bakane C++
Pratik Bakane C++Pratik Bakane C++
Pratik Bakane C++
 

Destaque

Phing101 or How to staff a build orchestra
Phing101 or How to staff a build orchestraPhing101 or How to staff a build orchestra
Phing101 or How to staff a build orchestraraphaelstolt
 
Gestalt2010 2
Gestalt2010 2Gestalt2010 2
Gestalt2010 2melikian
 
PHP.next: Traits
PHP.next: TraitsPHP.next: Traits
PHP.next: TraitsStefan Marr
 
DIL E Governance
DIL E GovernanceDIL E Governance
DIL E Governanceneha.gangal
 
Manua de educacion fisica
Manua de educacion fisicaManua de educacion fisica
Manua de educacion fisicaMINEDU
 
Data Infosys Limited, Jaipur
Data Infosys Limited, JaipurData Infosys Limited, Jaipur
Data Infosys Limited, Jaipurneha.gangal
 

Destaque (9)

Coer2 Intro
Coer2 IntroCoer2 Intro
Coer2 Intro
 
Phing101 or How to staff a build orchestra
Phing101 or How to staff a build orchestraPhing101 or How to staff a build orchestra
Phing101 or How to staff a build orchestra
 
Gestalt2010 2
Gestalt2010 2Gestalt2010 2
Gestalt2010 2
 
PHP.next: Traits
PHP.next: TraitsPHP.next: Traits
PHP.next: Traits
 
DIL E Governance
DIL E GovernanceDIL E Governance
DIL E Governance
 
PresentacióN
PresentacióNPresentacióN
PresentacióN
 
Manua de educacion fisica
Manua de educacion fisicaManua de educacion fisica
Manua de educacion fisica
 
Data Infosys Limited, Jaipur
Data Infosys Limited, JaipurData Infosys Limited, Jaipur
Data Infosys Limited, Jaipur
 
Beyond Frameworks
Beyond FrameworksBeyond Frameworks
Beyond Frameworks
 

Semelhante a Final ds record

Most Important C language program
Most Important C language programMost Important C language program
Most Important C language programTEJVEER SINGH
 
Singly linked list.pptx
Singly linked list.pptxSingly linked list.pptx
Singly linked list.pptxSanthiya S
 
For this homework, you will write a program to create and manipulate.pdf
For this homework, you will write a program to create and manipulate.pdfFor this homework, you will write a program to create and manipulate.pdf
For this homework, you will write a program to create and manipulate.pdfherminaherman
 
Data Structure using C
Data Structure using CData Structure using C
Data Structure using CBilal Mirza
 
Data Structure Project File
Data Structure Project FileData Structure Project File
Data Structure Project FileDeyvessh kumar
 
Practical_File_Of_Data_Structure.pdf
Practical_File_Of_Data_Structure.pdfPractical_File_Of_Data_Structure.pdf
Practical_File_Of_Data_Structure.pdfVishwasChoclaty1
 
VTU DSA Lab Manual
VTU DSA Lab ManualVTU DSA Lab Manual
VTU DSA Lab ManualAkhilaaReddy
 
Mouse programming in c
Mouse programming in cMouse programming in c
Mouse programming in cgkgaur1987
 
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYDATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYMalikireddy Bramhananda Reddy
 
Data Structures Practical File
Data Structures Practical File Data Structures Practical File
Data Structures Practical File Harjinder Singh
 
35787646 system-software-lab-manual
35787646 system-software-lab-manual35787646 system-software-lab-manual
35787646 system-software-lab-manualNaveen Kumar
 
IN C LANGUAGE- I've been trying to finish this program for the last fe.docx
IN C LANGUAGE- I've been trying to finish this program for the last fe.docxIN C LANGUAGE- I've been trying to finish this program for the last fe.docx
IN C LANGUAGE- I've been trying to finish this program for the last fe.docxGordonpACKellyb
 
Ds lab manual by s.k.rath
Ds lab manual by s.k.rathDs lab manual by s.k.rath
Ds lab manual by s.k.rathSANTOSH RATH
 
Basic c programs updated on 31.8.2020
Basic c programs updated on 31.8.2020Basic c programs updated on 31.8.2020
Basic c programs updated on 31.8.2020vrgokila
 

Semelhante a Final ds record (20)

Most Important C language program
Most Important C language programMost Important C language program
Most Important C language program
 
DataStructures notes
DataStructures notesDataStructures notes
DataStructures notes
 
7 functions
7  functions7  functions
7 functions
 
Singly linked list.pptx
Singly linked list.pptxSingly linked list.pptx
Singly linked list.pptx
 
For this homework, you will write a program to create and manipulate.pdf
For this homework, you will write a program to create and manipulate.pdfFor this homework, you will write a program to create and manipulate.pdf
For this homework, you will write a program to create and manipulate.pdf
 
01 list using array
01 list using array01 list using array
01 list using array
 
Data Structure
Data StructureData Structure
Data Structure
 
Data Structure using C
Data Structure using CData Structure using C
Data Structure using C
 
Data Structure Project File
Data Structure Project FileData Structure Project File
Data Structure Project File
 
Practical_File_Of_Data_Structure.pdf
Practical_File_Of_Data_Structure.pdfPractical_File_Of_Data_Structure.pdf
Practical_File_Of_Data_Structure.pdf
 
VTU DSA Lab Manual
VTU DSA Lab ManualVTU DSA Lab Manual
VTU DSA Lab Manual
 
Mouse programming in c
Mouse programming in cMouse programming in c
Mouse programming in c
 
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYDATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
 
Data Structures Practical File
Data Structures Practical File Data Structures Practical File
Data Structures Practical File
 
Data struture lab
Data struture labData struture lab
Data struture lab
 
C program
C programC program
C program
 
35787646 system-software-lab-manual
35787646 system-software-lab-manual35787646 system-software-lab-manual
35787646 system-software-lab-manual
 
IN C LANGUAGE- I've been trying to finish this program for the last fe.docx
IN C LANGUAGE- I've been trying to finish this program for the last fe.docxIN C LANGUAGE- I've been trying to finish this program for the last fe.docx
IN C LANGUAGE- I've been trying to finish this program for the last fe.docx
 
Ds lab manual by s.k.rath
Ds lab manual by s.k.rathDs lab manual by s.k.rath
Ds lab manual by s.k.rath
 
Basic c programs updated on 31.8.2020
Basic c programs updated on 31.8.2020Basic c programs updated on 31.8.2020
Basic c programs updated on 31.8.2020
 

Último

Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 

Último (20)

Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 

Final ds record

  • 1. Ex no –1(A) IMPLEMENTATION OF SINGLY LINKED LIST AIM: To write a c program to implement singly linked list. ALGORITHM: Step1: Start the program. Step2: Include the required header files at the top of the program. Step3: Create a structure named node and declare variables to denote a node for singly linked list. Step4: In the create () method, check whether the head is NULL or not. If it is NULL, then get the number of nodes from user and get data for each node that are created. Step5: In the insert () method, check whether the head is NULL or not. If it is NOT NULL, then get the position from the user and then insert into list. Step6: In the delete () method, check whether the head is NULL or not. If it is NOT NULL, then get the position to be deleted from the user. Step7: Insert and delete according to the position. Step8: In display () method, print the elements of singly linked list. Step9: In main () method, use switch case statement to invoke the methods according to the user choice entered. Step10: End of the program. 1
  • 2. PROGRAM: #include<conio.h> #include<stdio.h> void creation(int); void display(); void insertion(int,int); void deletion(int); struct list { int num; struct list *next; }*head, *l; void main() { int n1,ch,pos,val; clrscr(); do { printf("n1.creationn2.insertionn3.deletionn4.displayn5.exitn"); printf("nenter ur choice : "); scanf("%d",&ch); switch(ch) { case 1: creation(n1); break; case 2: printf("nnenter the postion in which to be inserted : "); scanf("%d",&pos); printf("nnenter the value : "); scanf("%d",&val); insertion(pos,val); break; case 3: printf("nnenter the position to be deleted : "); scanf("%d",&pos); deletion(pos); break; case 4: display(); getch(); break; case 5: exit(0); } }while(ch!=5); 2
  • 3. getch(); } void creation(int n1) { int i,n; head=((struct list *)malloc(sizeof(struct list))); l=head; printf("nEnter the no of nodes:"); scanf("%d",&n1); for(i=0;i<n1;i++) { printf("enter the %d node : ",i+1); scanf("%d",&n); l->num=n; l->next=((struct list *)malloc(sizeof(struct list))); l=l->next; } l->next=0; } void display() { l=head; printf("nthe nodes entered are : "); while(l->next>0) { printf("%dt",l->num); l=l->next; } printf("null"); } void insertion(pos,val) { int i; struct list *x,*y; l=head; i=2; if(pos==1) { x=((struct list *)malloc(sizeof(struct list))); x->num=val; x->next=l; head=x; } else { while(l->next>0) 3
  • 4. { if(pos==i-1) { x=((struct list *)malloc(sizeof(struct list))); x->num=val; x->next=l; y->next=x; } y=l; l=l->next; i++; } } } void deletion(pos) { int i; struct list *y; l=head; i=1; if(pos==1) { head=l->next; } else { while(l->next>0) { if(pos==i) { l=l->next; y->next=l; break; } y=l; l=l->next; i++; } } } 4
  • 5. INPUT & OUTPUT: 1.creation 2.insertion 3.deletion 4.display 5.exit enter ur choice : 1 Enter the no of nodes:2 enter the 1 node : 1 enter the 2 node : 2 1.creation 2.insertion 3.deletion 4.display 5.exit enter ur choice : 2 enter the postion in which to be inserted : 1 enter the value : 6 1.creation 2.insertion 3.deletion 4.display 5.exit enter ur choice : 4 the nodes entered are : 6 1 2 null 1.creation 2.insertion 3.deletion 4.display 5.exit enter ur choice : 2 enter the postion in which to be inserted : 2 enter the value : 4 1.creation 2.insertion 3.deletion 4.display 5.exit enter ur choice :2 enter the postion in which to be inserted : 2 5
  • 6. enter the value : 4 1.creation 2.insertion 3.deletion 4.display 5.exit enter ur choice : 3 enter the position to be deleted : 2 1.creation 2.insertion 3.deletion 4.display 5.exit enter ur choice : 4 the nodes entered are : 6 1 2 null 1.creation 2.insertion 3.deletion 4.display 5.exit enter ur choice : 5<Exiting> RESULT: Thus the program for program for implementation of singly linked list has been completed successfully and output verified. Ex no –1(B) IMPLEMENTATION OF DOUBLY 6
  • 7. LINKED LIST AIM: To write a c program to implement doubly linked list. ALGORITHM: Step1: Start the program. Step2: Include the required header files at the top of the program. Step3: Create a structure named node and declare variables to denote a node for doubly linked list. Step4: In the create () method, get the number of nodes and iterate the loop to get data for each node that are created. Step5: In the insert () method, get the position from the user. If it is valid position, get the data for a node and give forward link and backward link. Step6: In the delete () method, get the position to be deleted. If it is valid position, by rearranging forward link and backward link to delete the node from the list. Step7: Insert and delete according to the valid position. Step8: In display () method, print the elements of doubly linked list. Step9: In main () method, use switch case statement to invoke the methods according to the user choice entered. Step10: End of the program. PROGRAM: #include<stdio.h> 7
  • 8. #include<conio.h> struct list { int data; struct list *llink,*rlink; }; typedef struct list node; node *head=NULL, *tail=NULL; void ins(node *head) { node *p,*q; int d,t; q=(node*)malloc( sizeof(node) ); printf("enter the element into the list :"); scanf("%d" ,&d); q->data=d; q->rlink=q-> llink=NULL; p=head; do { if(p->rlink->llink==NULL) { q->llink=head; head->rlink= q; q->rlink=tail; tail->llink= q; t=1; } else if(p->rlink->data>d) { p->rlink->llink= q; q->llink=p; q->rlink=p-> rlink; p->rlink=q; t=1; } else p=p->rlink; } while(t!=1); while(p->llink!=NULL) p=p->llink; head=p; } void delete(node *head) { 8
  • 9. int d,t; node *p, *fntptr; printf("enter the deleted element :"); scanf("%d",& d); p=head; do { fntptr=p->rlink; if(p->rlink->data==d) { fntptr=fntptr->rlink; p->rlink=fntptr; fntptr=p; t=1; } else if(d>p->rlink->data) p=fntptr; else { puts("n data not found n"); t=1; } } while(t!=1); while(p->llink!=NULL) p=p->llink; head=p; } void dis(node *head) { node *p; p=head->rlink; while(p->rlink!=NULL) { printf("%d-> ",p->data) ; p=p->rlink; } while(p->llink!=NULL) p=p->rlink; head=p; printf("NULLn"); } void main() { int ch; 9
  • 10. clrscr(); printf(" Doubly linked list operationsn" ); printf("1.insert 2.delete 3.display 4.exit n"); head=(node*) malloc(sizeof( node)); tail=(node*) malloc(sizeof( node)); head->data=0; head->llink= NULL; tail->data=1000; tail->rlink= NULL; head->rlink= tail; tail->llink= head; do { printf("enter your choice :"); scanf("%d",& ch); switch(ch) { case 1: ins(head); break; case 2: delete(head) ; break; case 3: dis(head); getch(); } } while(ch!=4) ; free(head); free(tail); } INPUT & OUTPUT: 10
  • 11. Doubly linked list operations 1.insert 2.delete 3.display 4.exit enter your choice :1 enter the element into the list :1 enter your choice :1 enter the element into the list :2 enter your choice :3 1-> 2-> NULL enter your choice :2 enter the deleted element :4 data not found enter your choice :2 enter the deleted element :1 enter your choice :3 2-> NULL enter your choice :4 <Exiting> RESULT: Thus the program for program for implementation of doubly linked list has been completed successfully and output verified. Ex no – 2 POLYNOMIAL ADDITION 11
  • 12. AIM: To write a c program represent a polynomial as a linked list and write functions for polynomial addition . ALGORITHM: Step1: Start the program. Step2: Include the required header files at the top of the program. Step3: Declare the needed variables and initialize them. Step4: Get the value of co – efficient and exponent value of two polynomial expressions Step5: Compare the exponent of two polynomial expressions. Step6: If the exponent values are same add the polynomial co – efficient. Step7: If the exponent values are different add the biggest exponent’s co – efficient value in to the result polynomial. Step8: Print the result polynomial expression. Step9: End of the program. PROGRAM: #include<stdio.h> #include<conio.h> 12
  • 13. typedef struct poly { int coeff; int expo; }p; p p1[10],p2[10],p3[10]; void main() { int t1,t2,t3; int read(p p1[10]); int add(p p1[10],p p2[10],int t1,int t2,p p3[10]); void print(p p2[10],int t2); void printo(p pp[10],int t2); t1=read(p1); print(p1,t1); t2=read(p2); print(p2,t2); t3=add(p1,p2,t1,t2,p3); printo(p3,t3); getch(); } int read(p p[10]) { int t1,i; printf("nEnter the total no of terms in polynomial:"); scanf("%d",&t1); printf("Enter the coefficient and exponent in descending order"); for(i=0;i<t1;i++) scanf("%d%d",&p[i].coeff,&p[i].expo); return(t1); } int add(p p1[10],p p2[10],int t1,int t2,p p3[10]) { int i=0,j=0,k=0,t3; while(i<t1&&j<t2) { if(p1[i].expo==p2[j].expo) { p3[k].coeff=p1[i].coeff+p2[j].coeff; p3[k].expo=p1[i].expo; i++;j++;k++; } else if(p1[i].expo>p2[j].expo) { p3[k].coeff=p1[i].coeff; p3[k].expo=p1[i].expo; 13
  • 14. i++;k++; } else { p3[k].coeff=p2[j].coeff; p3[k].expo=p2[j].expo; j++;k++; } } while(i<t1) { p3[k].coeff=p1[i].coeff; p3[k].expo=p1[i].expo; i++;k++; } while(j<t2) { p3[k].coeff=p2[j].coeff; p3[k].expo=p2[j].expo; j++;k++; } t3=k; return(t3); } void print(p pp[10],int term) { int k; printf("Printing the polynomial"); for(k=0;k<term-1;k++) printf("%dx^%d+",pp[k].coeff,pp[k].expo); printf("%dx^%d",pp[k].coeff,pp[k].expo); } void printo(p pp[10],int term) { int k; printf("nAddition of polynomial"); for(k=0;k<term-1;k++) printf("%dx^%d+",pp[k].coeff,pp[k].expo); printf("%dx^%d",pp[k].coeff,pp[k].expo); } INPUT & OUTPUT: 14
  • 15. Enter the total no of terms in polynomial:3 Enter the coefficient and exponent in descending order3 3 2 2 1 0 Printing the polynomial3x^3+2x^2+1x^0 Enter the total no of terms in polynomial:3 Enter the coefficient and exponent in descending order4 2 3 1 5 0 Printing the polynomial4x^2+3x^1+5x^0 Addition of polynomial3x^3+6x^2+3x^1+6x^0 RESULT: Thus the program for program for polynomial addition has been completed successfully and output verified. Ex no – 3 IMPLEMENTATION OF STACK 15
  • 16. AIM: To write a c program to implement stack operations using array. ALGORITHM: Step1: Start the program. Step2: Include the required header files at the top of the program. Step3: Declare the needed variables and initialize them. Step4: In push () operation, check whether the stack is full or not. If the stack is not full, insert the element into the stack by incrementing top value. Step5: In pop () operation, check whether the stack is empty or not. If the stack is not empty, delete the element from the stack by decrementing top value. Step6: In display () method, print the stack elements using for loop. Step7: In main () method, using switch case statement to invoke the methods according to the user choice entered. Step8: End of the program. PROGRAM: #include<stdio.h> 16
  • 17. #include<conio.h> #define size 10 int stack[size],top=-1; void push(); void pop(); void display(); void main() { int c; clrscr(); printf("nn1.pushn2.popn3.displayn4.Exit"); do { printf("nnEnter your choice::"); scanf("%d",&c); switch(c) { case 1: push(); break; case 2: pop(); break; case 3: printf("nnContents of stack ist"); display(); break; default: printf("nInvalid Choice"); exit(0); } }while(c<4); getch(); } void push() { int b; if(top>size-1) { printf("nstack over flow"); return; } else { printf("nEnter the number to push into the stack:"); scanf("%d",&b); 17
  • 18. top++; stack[top]=b; return; } } void pop() { int res; if(top==0) { printf("nStack Underflow"); } else { res=stack[top]; top--; printf("nDeleted element is %d",res); return; } } void display() { int i; if(top==-1) { printf("nStack Under flow"); return; } else { for(i=top;i>=0;i--) printf("%d",stack[i]); } } INPUT & OUTPUT: 1.push 18
  • 19. 2.pop 3.display 4.Exit Enter your choice::1 Enter the number to push into the stack:1 Enter your choice::1 Enter the number to push into the stack:2 Enter your choice::1 Enter the number to push into the stack:3 Enter your choice::3 Contents of stack is 3 2 1 Enter your choice::2 Deleted element is 3 Enter your choice::3 Contents of stack is 2 1 Enter your choice:: 4 <Exiting> RESULT: Thus the program for program for implementation of stack using array has been completed successfully and output verified. Ex.No:4 INFIX TO POSTFIX CONVERSION 19
  • 20. AIM: Write a C program to Implement stack and use it to convert infix to postfix expression ALGORITHM: Step1: Start the program. Step2: Initialize the stack. Step3: Read the given infix expression into string called infix. Step4: If the character is an operand, place it on the output. Step5: If the character is an operator, push it on to the stack. if the stack operator has a higher or equal priority than input operator then pop that operator from the stack and place it onto the output. Step6: If the character is a left parenthesis, push it onto the stack. Step7: If the character is a right parenthesis, pop all operators from the stack till it encounters left parenthesis, discard both the parenthesis in the output. Step8: Display the postfix expression for the given infix expression. Step9: End the program. PROGRAM: #include<stdio.h> 20
  • 21. #include<conio.h> #include<stdlib.h> char inf[40],post[40]; int top=0,st[20]; void postfix(); void push(int); char pop(); void main() { clrscr(): printf(“Enter the infix expression:”); scanf(“%s”,&inf); postfix(); getch(); } void postfix() { int i,j=0; for(i=0;inf[i]!=’0’;i++) { switch(inf[i]) { case ‘+’: while(st[top>=1) post[j++]=pop(); push(1); break; case ‘-’: while(st[top>=1) post[j++]=pop(); push(2); break; case ‘*’: while(st[top>=3) post[j++]=pop(); push(3); break; case ‘/’: while(st[top>=3) post[j++]=pop(); push(4); break; case ‘^’: while(st[top>=4) post[j++]=pop(); push(5); break; case ‘(’: 21
  • 22. push(0); break; case ‘)’: while(st[top!=0) post[j++]=pop(); top--; break; default: post[j++]=inf[i]; } } while(top>0) post[j++]=pop(); printf(“nPostfix expression is %s”,post); } void push(int ele) { top++; st[top]=ele; } char pop() { int e1; char e; e1=st[top]; top--; switch(e1) { case 1: e=’+’; break; case 2: e=’-’; break; case 3: e=’*’; break; case 4: e=’/’; break; case 5: e=’^’; break; } return(e); } INPUT & OUTPUT: Enter the infix expression: a+b 22
  • 23. Postfix expression is ab+ RESULT: Thus the program for program for infix to postfix expression conversion has been completed successfully and output verified. Ex no – 5 IMPLEMENTATION OF QUEUE 23
  • 24. AIM: To write a c program to implement queue operations using array. ALGORITHM: Step1: Start the program. Step2: Include the required header files at the top of the program. Step3: Declare the needed variables and initialize them. Step4: In insert () operation, check whether the queue is full or not. If the queue is not full, insert the element into the queue by incrementing rear value. Step5: In delete () operation, check whether the queue is empty or not. If the queue is not empty, delete the element from the queue by incrementing front value. Step6: In display () method, print the queue elements using for loop. Step7: In main () method, using switch case statement to invoke the methods according to the user choice entered. Step8: End of the program. PROGRAM: #include <stdio.h> 24
  • 25. #include<conio.h> #define MAXSIZE 2 int q[MAXSIZE]; int front=-1,rear=-1,ch; void main() { void insert(); int del(); void display(); clrscr(); do { printf("nMAIN MENU:1.Insert 2.Delete 3.Display 4.ExitnEnter ur choice:"); scanf("%d",&ch); switch(ch) { case 1: insert(); break; case 2: del(); break; case 3: display(); break; case 4: exit(0); default: printf("Invalid Choice ... "); } } while(ch!=4); } void insert() { int num; if(rear==(MAXSIZE-1)) { printf("QUEUE FULL"); return; } else { printf("Enter the no:"); scanf("%d",&num); rear=rear+1; q[rear]=num; if(front==-1) front++; 25
  • 26. }return; } int del() { int num; if(front==-1) { printf("QUEUE EMPTY"); return 0; } else { num=q[front]; printf("nDeleted element is %d",q[front]); front++; } return(num); } void display() { int i; if(front==-1) { printf("Queue empty"); return; } else { printf("nQueue elements are:"); for(i=front;i<=rear;i++) printf("%dt",q[i]); } } INPUT & OUTPUT: 26
  • 27. MAIN MENU:1.Insert 2.Delete 3.Display 4.Exit Enter ur choice:3 Queue empty MAIN MENU:1.Insert 2.Delete 3.Display 4.Exit Enter ur choice:1 Enter the no:1 MAIN MENU:1.Insert 2.Delete 3.Display 4.Exit Enter ur choice:1 Enter the no:2 MAIN MENU:1.Insert 2.Delete 3.Display 4.Exit Enter ur choice:1 QUEUE FULL MAIN MENU:1.Insert 2.Delete 3.Display 4.Exit Enter ur choice:2 Deleted element is 1 MAIN MENU:1.Insert 2.Delete 3.Display 4.Exit Enter ur choice:2 Deleted element is 2 MAIN MENU:1.Insert 2.Delete 3.Display 4.Exit Enter ur choice:3 Queue elements are: MAIN MENU:1.Insert 2.Delete 3.Display 4.Exit Enter ur choice:4 <Exiting> RESULT: Thus the program for program for implementation of queue using array has been completed successfully and output verified. Ex no – 6 IMPLEMENTATION OF CIRCULAR 27
  • 28. QUEUE AIM: To write a c program to implement circular queue using array. ALGORITHM: Step1: Start the program. Step2: Include the required header files at the top of the program. Step3: Declare the needed variables and initialize them. Step4: In insert () operation, check whether the queue is full or not. If the queue is not full, check the front value if no element is there, insert the element into the queue in front position. Step5: In delete () operation, check whether the queue is empty or not. If the queue is not empty, delete the element from the queue by incrementing front value. Step6: In display () method, print the queue elements using for loop. Step7: In main () method, using switch case statement to invoke the methods according to the user choice entered. Step8: End of the program. 28
  • 29. PROGRAM: #include<stdio.h> #include<conio.h> #define max 5 int q[max]; int front=-1; int rear=-1; void main() { int ch; clrscr(); while(1) { printf("enter your choice"); scanf("%d",&ch); switch(ch) { case 1: insert(); break; case 2: del(); break; case 3: display(); break; case 4: exit(1); default: printf("in wrong choice"); } } } insert() { int item; if((front==0&&rear==max-1)||(front==rear+1)) { printf("n queue overflow"); return; } if (front==-1) { front=0; rear=0; } 29
  • 30. else if(rear==max-1) rear=0; else rear=rear+1; printf("enter the element"); scanf("%d",&item); q[rear]=item; } del() { if(front==-1) { printf("queue underflown"); return; } printf("element deleted from queue is %d:n",q[front]); if(front==rear) { rear=-1; front=-1; } else if(front==max-1) front=0; else front=front+1; } display() { int fpos=front,rpos=rear; if(front==-1) { printf("queue is emptyn"); return; } printf("queue elements:n"); if(fpos<=rpos) while(fpos<=rpos) { printf("%dn",q[fpos]); fpos++; } else { 30
  • 32. INPUT & OUTPUT: 1.insert 2.delete 3.display 4.quit enter your choice1 enter the element1 1.insert 2.delete 3.display 4.quit enter your choice1 enter the element2 1.insert 2.delete 3.display 4.quit enter your choice3 queue elements: 1 2 1.insert 2.delete 3.display 4.quit enter your choice2 element deleted from queue is 1: 1.insert 2.delete 3.display 4.quit enter your choice3 queue elements: 2 1.insert 2.delete 3.display 4.quit enter your choice4 <Exiting> RESULT: Thus the program for implementation of circular queue has been completed successfully and output verified. 32
  • 33. Ex no – 7 IMPLEMENTATION OF EXPRESSION TREE AIM: To write a c program to implement an expression tree. Produce its pre-order, in- order, and post order traversals. ALGORITHM: Step1: Start the program. Step2: Include the required header files at the top of the program. Step3: Declare the function inorder(), postorder(), preorder(). Step4: Read the input in the form of postfix expression. Step5: In inorder () function, traversal will be from left child-->root-->right child. Step6: In preorder () function, traversal will be from root-->left child--> right child. Step7: In postorder () function, traversal will be from left child--> right child-->root. Step8: In main () method, using switch case statement to invoke the methods according to the user choice entered. Step9: End of the program. 33
  • 34. PROGRAM: #include<stdio.h> #include<conio.h> #include<stdlib.h> #define size 20 typedef struct node { char data; struct node *left; struct node *right; }btree; btree *stack[size]; int top; void main() { btree *root; char exp[80]; btree *create(char exp[80]); void inorder(btree *root); void preorder(btree *root); void postorder(btree *root); clrscr(); printf(“nEnter the postfix expression:”); scanf(“%s”,&exp); top=-1; root=create(exp); printf(“nInorder traversal:”); inorder(root); printf(“nPreorder traversal:”); preorder(root); printf(“nPostorder traversal:”); postorder(root); getch(); } btree *create(char exp[]) { btree *temp; int pos; char ch; void push(btree *); btree *pop(); pos=0; ch=exp[pos]; while(ch!=’0’) { temp=(btree *)malloc(sizeof(btree)); 34
  • 35. temp->left=temp->right=NULL; temp->data=ch; if(isalpha(ch)) push(temp); else if(ch==’+’||ch==’-‘||ch==’*’||ch==’/’) { temp->right=pop(); temp->left=pop(); push(temp); } else printf(“nInvalid character in expression”); pos++; ch=exp[pos]; } temp=pop(); return(temp); } void push(btree *node) { if(top+1>=size) printf(“Error:Stack is full”); top++; stack[top]=node; } btree *pop() { btree *node; if(top==-1) printf(“Error:Stack empty”); node=stack[top]; top--; return(node); } void inorder(btree *root) { btree *temp; temp=root; if(temp!=NULL) { inorder(temp->left); printf(“%c”,temp->data); inorder(temp->right); } } void preorder(btree *root) { 35
  • 36. btree *temp; temp=root; if(temp!=NULL) { printf(“%c”,temp->data); preorder(temp->left); preorder(temp->right); } } void postorder(btree *root) { btree *temp; temp=root; if(temp!=NULL) { postorder(temp->left); postorder(temp->right); printf(“%c”,temp->data); } } 36
  • 37. INPUT & OUTPUT: Enter the postfix expression:ab+cd-* Inorder traversal:a+b*c-d Preorder traversal:*+ab-cd Postorder traversal:ab+cd-* RESULT: Thus the program for implementation of expression tree and its traversal order has been completed successfully and output verified. 37
  • 38. Ex no – 8 IMPLEMENTATION OF BINARY SEARCH TREE AIM: To write a c program to implement binary search tree. ALGORITHM: Step1: Start the program. Step2: Include the required header files at the top of the program. Step3: Declare the function add(),search(), findmin(),findmax() and display(). Step4: In main () method, using switch case statement to invoke the methods according to the user choice entered. Step5: In add () function, get the number from user and insert it into tree. Step6: In search () function, the number given for search will be traversed and result of the searching will be displayed. Step7: In findmin () function, display the minimum element in the tree Step8: In findmax () function, display the maximum element in the tree Step8: In display() function, the binary search tree will be displayed. Step9: End of the program. 38
  • 39. PROGRAM: #include<stdio.h> #include<conio.h> #include<stdlib.h> typedef struct node { int data; struct node *left, *right; }*nptr; nptr root,t,p,q; void add(); void search(); void findmin(); void findmax(); void disp(nptr,int,int,int); void main() { int ch; root=NULL; while(1) { printf(“1.Create 2.Search 3.Display 4.Findmin 5.Findmax 6.ExitnEnter ur choice:”); scanf(“%d”,&ch); switch(ch) { case 1: add(); break; case 2: search(); break; case 3: clrscr(); disp(root,40,7,16); break; case 4: findmin(); break; case 5: findmax(); break; case 6: exit(0); } } } 39
  • 40. void add() { int x; t=(nptr)malloc(sizeof(struct node)); printf(“nEnter data:”); scanf(“%d”,&x); t->data=x; t->left=NULL; t->right=NULL; if (root==NULL) root=t; else { p=q=root; while(q!=NULL&&x!=p->data) { p=q; if(x<p->data) q=p->left; else q=p->right; } if(x==p->data) printf(“%d is duplicate no n”,x); else if(x<p->data) p->left=t; else p->right=t; } } void search() { int x; printf(“Enter the element to search:”); scanf(“%d”,&x); p=q=root; while(q!=NULL&&x!=p->data) { p=q; if(x<p->data) q=p->left; else q=p->right; } if(x==p->data) printf(“Element is present”); 40
  • 41. else printf(“Element not present”); } void disp(nptr root,int col,int row,int wid) { gotoxy(col,row); if(root!=NULL) { printf(“%d”,root->data); disp(root->left,col-wid,row+2,wid/2); disp(root->right,col+wid,row+2,wid/2); } } void findmax() { t=root; while(t->right!=NULL) t=t->right; printf(Maximum value in BST is %d”,t->data); } void findmin() { t=root; while(t->left!=NULL) t=t->left; printf(Minimum value in BST is %d”,t->data); } 41
  • 42. INPUT & OUTPUT: 1.Create 2.Search 3.Display 4.Findmin 5.Findmax 6.Exit Enter ur choice:1 Enter data:10 1.Create 2.Search 3.Display 4.Findmin 5.Findmax 6.Exit Enter ur choice:1 Enter data:9 1.Create 2.Search 3.Display 4.Findmin 5.Findmax 6.Exit Enter ur choice:1 Enter data:8 1.Create 2.Search 3.Display 4.Findmin 5.Findmax 6.Exit Enter ur choice:1 Enter data:11 1.Create 2.Search 3.Display 4.Findmin 5.Findmax 6.Exit Enter ur choice:1 Enter data:12 1.Create 2.Search 3.Display 4.Findmin 5.Findmax 6.Exit Enter ur choice:3 10 9 11 8 12 1.Create 2.Search 3.Display 4.Findmin 5.Findmax 6.Exit Enter ur choice:2 Enter the element to search:8 Element is present 1.Create 2.Search 3.Display 4.Findmin 5.Findmax 6.Exit Enter ur choice:2 Enter the element to search:7 Element not present 1.Create 2.Search 3.Display 4.Findmin 5.Findmax 6.Exit Enter ur choice:4 Minimum value in BST is 8 1.Create 2.Search 3.Display 4.Findmin 5.Findmax 6.Exit Enter ur choice:5 Maximum value in BST is 12 1.Create 2.Search 3.Display 4.Findmin 5.Findmax 6.Exit Enter ur choice:6 <Exiting…..> RESULT: Thus the program for implementation of binary search tree has been completed successfully and output verified. 42
  • 43. Ex no – 9 IMPLEMENTATION OF PRIORITY QUEUE USING HEAPS AIM: To write a c program to implement priority queue using heap. ALGORITHM: Step1: Start the program. Step2: Include the required header files at the top of the program. Step3: Declare the needed variables and initialize them. Step4: By defining the priority queue, we can perform operations on heap. Step5: Insert an item arbitrarily at anywhere in the priority queue. Step6: Delete an item that has highest priority i.e. maximum value from the priority queue. This is called max heap. Step7: Delete an item that has lowest priority i.e. minimum value from the priority queue. This is called min heap. Step8: Print the contents of heap using for loop. Step9: End of the program. 43
  • 44. PROGRAM: #include<stdio.h> #include<conio.h> #define size 5 void main(void) { int rear,front,que[size],choice; int qfull(int rear),qempty(int rear,int front); int insert(int que[size],int rear,int front); int delet(int que[size],int front); void display(int que[size],int rear,int front); clrscr(); front=0; rear=-1; do { printf("nMainmenu1:insert 2:delete 3:display 4.Exitnenter ur choice: "); scanf("%d",&choice); switch(choice) { case 1:if(qfull(rear)) printf("nqueue is full"); else rear=insert(que,rear,front); break; case 2: if(qempty(rear,front)) printf("ncannot delete element"); else front=delet(que,front); break; case 3: if(qempty(rear,front)) printf("nqueue is empty"); else display(que,rear,front); break; case 4: exit(0); default: printf("nwrong choice"); break; } }while(choice!=4); getch(); } 44
  • 45. int insert(int que[size],int rear,int front) { int item,j; printf("nenter the element : "); scanf("%d",&item); if(front==-1) front++; j=rear; while(j>=0&&item<que[j]) {que[j+1]=que[j]; j--; } que[j+1]=item; rear=rear+1; return rear; } int qfull(int rear) { if(rear==size-1) return 1; else return 0; } int delet(int que[size],int front) { int item; item=que[front]; printf("nthe item deleted is %d",item); front++; return front; } qempty(int rear,int front) { if((front==-1)||(front>rear)) return 1; else return 0; } void display(int que[size],int rear,int front) { int i; printf("nthe queue is :"); for(i=front;i<=rear;i++) printf(" %d",que[i]); } 45
  • 46. INPUT & OUTPUT: Mainmenu1:insert 2:delete 3:display 4.Exit enter ur choice: 1 enter the element : 1 Mainmenu1:insert 2:delete 3:display 4.Exit enter ur choice: 1 enter the element : 2 Mainmenu1:insert 2:delete 3:display 4.Exit enter ur choice: 1 enter the element : 3 Mainmenu1:insert 2:delete 3:display 4.Exit enter ur choice: 3 the queue is : 1 2 3 Mainmenu1:insert 2:delete 3:display 4.Exit enter ur choice: 2 the item deleted is 1 Mainmenu1:insert 2:delete 3:display 4.Exit enter ur choice: 2 the item deleted is 2 Mainmenu1:insert 2:delete 3:display 4.Exit enter ur choice: 2 the item deleted is 3 Mainmenu1:insert 2:delete 3:display 4.Exit enter ur choice: 2 cannot delete element Mainmenu1:insert 2:delete 3:display 4.Exit enter ur choice: 3 queue is empty Mainmenu1:insert 2:delete 3:display 4.Exit enter ur choice: 4<Exiting> RESULT: Thus the program for implementation of priority queue using heap has been completed successfully and output verified. 46
  • 47. Ex no – 10 IMPLEMENTATION OF HASHING TECHINQUE AIM: To write a c program to implement hashing by linear probing. ALGORITHM: Step1: Start the program. Step2: Include the required header files at the top of the program. Step3: Declare and initialize needed variables. Step4: Get the size of the hash table from the user and makes the indices sequentially based on size. Step5: Then get the integer number from the user . And compute the hash function for that number using the given formula. Hash function= (int) e % size of the hash table Step6: Finally, store the number in corresponding location in the hash table. Step7: Check whether the hash table is empty or full during insertion and deletion function. Step8: Print the contents of hash table whenever the user needs to view. Step9: End of the program. 47
  • 48. PROGRAM: #include<stdio.h> #include<conio.h> #include<stdlib.h> #define MAX 10 void main() { int a[MAX],num,key,i; char ans; int create(int); void linear_prob(int [],int,int),display(int []); clrscr(); printf("nCollision handling by linear probing"); for(i=0;i<MAX;i++) a[i]=-1; do { printf("nEnter the number"); scanf("%d",&num); key=create(num); linear_prob(a,key,num); printf("ndo you wish to continue? (y/n)"); ans=getche(); }while(ans=='y'); display(a); getch(); } int create(int num) { int key; key=num%10; return key; } void linear_prob(int a[MAX],int key,int num) { int flag,i,count=0; void display(int a[]); flag=0; if(a[key]==-1) a[key]=num; else { i=0; while(i<MAX) { if(a[i]!=-1) 48
  • 49. count++; i++; } if(count==MAX) { printf("nhash table is full"); display(a); getch(); exit(1); } for(i=key+1;i<MAX;i++) if(a[i]==-1) { a[i]=num; flag=1; break; } for(i=0;i<key&&flag==0;i++) if(a[i]==-1) { a[i]=num; flag=1; break; }}} void display(int a[MAX]) { int i; printf("nthe hash table"); for(i=0;i<MAX;i++) printf("n%dt%d",i,a[i]); } 49
  • 50. INPUT & OUTPUT: Collision handling by linear probing Enter the number33 do you wish to continue? (y/n)y Enter the number83 do you wish to continue? (y/n)y Enter the number35 do you wish to continue? (y/n)y Enter the number42 do you wish to continue? (y/n)y Enter the number74 do you wish to continue? (y/n)n the hash table 0 -1 1 -1 2 42 3 33 4 83 5 35 6 74 7 -1 8 -1 9 -1 RESULT: Thus the program for implementation of hashing by linear probing has been completed successfully and output verified. 50
  • 51. Ex no – 11 IMPLEMENTATION OF TOPOLOGICAL SORTING AIM: To write a c program to implement topological sorting. ALGORITHM: Step1: Start the program. Step2: Include the required header files at the top of the program. Step3: Declare the function push(), pop(), ts(). Step4: In push () function, check whether the stack is full or not. If the stack is not full, insert the vertex into the stack by incrementing top value. Step5: In pop () operation, check whether the stack is empty or not. If the stack is not empty, get the vertex from the stack by decrementing top value. Step6: In ts () function, traversal order for the given graph is found. Step7: In main () method, get the adjacency matrix for given number of vertices from user and call the required function. Step8: End of the program. 51
  • 52. PROGRAM: #include<stdio.h> #include<conio.h> #define max 30 int stack[max],top=-1; int push(int v); int pop(int *v); int ts(int mat[max][max],int n,int order[max]); void main() { int i,j,n,mat[max][max],order[max],succ; clrscr(); printf("nenter the no. of vertices : "); scanf("%d",&n); printf("nenter adjacency matrix :n"); for(i=0;i<n;i++) for(j=0;j<n;j++) scanf("%d",&mat[i][j]); succ=ts(mat,n,order); if(succ==1) {printf("nnthe directed graph is acyclic"); printf("nnthe topological sorted order isn"); for(i=0;i<n;i++) printf("%dt",order[i]+1); } else printf("nthe directed graph is not acyclic"); getch(); } int push(int v) { if(top==max-1) return 0; else stack[++top]=v; return -1; } int pop(int *v) { if(top==-1) return 0; else *v=stack[top--]; return -1; } int ts(int mat[max][max],int n,int order[max]) 52
  • 54. INPUT & OUTPUT: Enter the no. of vertices : 7 Enter adjacency matrix: 0111000 0001100 0000010 0010011 0001001 0000000 0000010 The directed graph is acyclic The topological sorted order is 1 2 5 4 7 3 6 RESULT: Thus the program for implementation of topological sorting has been completed successfully and output verified. 54
  • 55. Ex no – 12 IMPLEMENTATION OF DIJKSTRA’S ALGORITHM AIM: To write a c program to implement dijkstra’s algorithm. ALGORITHM: Step1: Start the program. Step2: Include the required header files at the top of the program. Step3: Get the number of vertices from the user and get cost for each vertex. Step4: The general algorithm for this process is as follows, o select a starting node o build the initial fringe from nodes connected to the starting node o while we are not at the destination node do • choose the fringe node with the shortest path to the starting node • add that node and its edge to the tree • update the fringe by:  adding nodes to the fringe connected to the new node  for each node in the fringe do update its edge one connected to the tree on the shortest path to the starting node  end for o end while Step5: Print the shortest path. Step6: End of the program. 55
  • 56. PROGRAM: #include<stdio.h> #include<conio.h> #define INFINITY 1000 int a[10][10],b[10][10]; int i,j,k,n; void input(); void initialize(); void spath(); void display(); void input() { printf("nt *** DIJKSTRA’S ALGORITHM ***"); printf("n enter the no of vertices:"); scanf("%d",&n); for(i=1;i<=n;i++) for(j=1;j<=n;j++) { if(i!=j) { printf("cost between %d to %d",i,j); scanf("%d",&a[i][j]); } } } void initialize() { for(i=1;i<=n;i++) a[i][j]=0; for(i=1;i<=n;i++) for(j=1;j<=n;j++) { b[i][j]=a[i][j]; if(!a[i][j] && (i!=j)) { b[i][j]=INFINITY; } } } void spath() { for(k=1;k<=n;k++) for(i=1;i<=n;i++) for(j=1;j<=n;j++) if((b[i][k] && b[k][j]) && (b[i][k]+b[k][j]<b[i][j])) { 56
  • 57. b[i][j]=b[i][k]+b[k][j]; } } void display() { i=1; if(i<n) { for(j=2;j<=n;j++) printf("Minimum cost FROM source vertex 1 TO %d is : %dn",j,b[i][j]); } } void main() { clrscr(); input(); initialize(); spath(); display(); getch(); } 57
  • 58. INPUT & OUTPUT: *** DIJKSTRA’S ALGORITHM *** enter the no of vertices: 5 cost between1—2: 2 cost between1—3: 1 cost between1—4: 0 cost between1—5: 0 cost between2—1: 2 cost between2—3: 5 cost between2—4: 4 cost between2—5: 0 cost between3—1: 1 cost between3—2: 5 cost between3—4: 3 cost between3—5: 2 cost between4—1: 0 cost between4—2: 4 cost between4—3: 3 cost between4—5: 6 cost between5—1: 0 cost between5—2: 0 cost between5—3: 2 cost between5—4: 6 minimum cost FROM 1 TO 2 is : 2 minimum cost FROM 1 TO 3 is : 1 minimum cost FROM 1 TO 4 is : 4 minimum cost FROM 1 TO 5 is : 3 RESULT: Thus the program for implementation of dijkstra’s algorithm has been completed successfully and output verified. 58
  • 59. Ex no – 13(A) IMPLEMENTATION OF PRIM’S ALGORITHM AIM: To write a c program to implement prim’s algorithm. ALGORITHM: Step1: Start the program. Step2: Include the required header files at the top of the program. Step3: Get the number of nodes from the user and get weight for each vertex. Step4: The general algorithm for this process is as follows, o select a starting node. o build the initial fringe from nodes connected to the starting node o while there are nodes left do  choose the edge to the fringe of the smallest weight  add the associated node to the tree  update the fringe by: • adding nodes to the fringe connected to the new node • updating the edges to the fringe so that they are the smallest o end while Step5: Print the minimal spanning tree. Step6: End of the program. 59
  • 60. PROGRAM: #include<stdio.h> #include<conio.h> void main() { int lowcost[20],min; int n,noe,i,j,k,v,closest[20],u,cost[50][50]; clrscr(); printf("ENTER THE NO OF NODES:"); scanf("%d",&n); printf("nENTER NO OF EDGES:"); scanf("%d",&noe); for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { cost[i][j]=1000; } } for(i=1;i<=noe;i++) { printf("ENTER THE EDGE: "); scanf("%d%d",&u,&v); printf("ENTER COST OF EDGE:"); scanf("%d",&cost[u][v]); cost[v][u]=cost[u][v]; } printf("nThe output of minimum spanning tree will be...n"); for(i=2;i<=n;i++) { lowcost[i]=cost[1][i]; closest[i]=1; } for(i=2;i<=n;i++) { min=lowcost[2]; k=2; for(j=3;j<=n;j++) { if(lowcost[j]<min) { min=lowcost[j]; k=j; } 60
  • 61. } printf("%d ->%d:cost %dn",k,closest[k],lowcost[k]); lowcost[k]=2000; for(j=2;j<=n;j++) if((cost[k][j]<lowcost[j]) && (lowcost[j]<2000)) { lowcost[j]=cost[k][j]; closest[j]=k; } } getch(); } 61
  • 62. INPUT & OUTPUT: ENTER THE NO OF NODES:4 ENTER NO OF EDGES:5 ENTER THE EDGE: 1 2 ENTER COST OF EDGE:9 ENTER THE EDGE: 1 3 ENTER COST OF EDGE:3 ENTER THE EDGE: 1 4 ENTER COST OF EDGE:2 ENTER THE EDGE: 2 4 ENTER COST OF EDGE:1 ENTER THE EDGE: 3 4 ENTER COST OF EDGE:6 The output of minimum spanning tree will be... 4 ->1:cost 2 2 ->4:cost 1 3 ->1:cost 3 RESULT: Thus the program for implementation of prim’s algorithm has been completed successfully and output verified. 62
  • 63. Ex no – 13(B) IMPLEMENTATION OF KRUSKAL’S ALGORITHM AIM: To write a c program to implement kruskal’s algorithm. ALGORITHM: Step1: Start the program. Step2: Include the required header files at the top of the program. Step3: Get the number of nodes from the user and get weight for each node. Step4: Sort the edges in nondecreasing order by weight and initialize partition structure for finding the edges to be included in spanning tree. Step5: Print the minimum spanning tree. Step6: End of the program. 63
  • 64. PROGRAM: #include<stdio.h> #include<conio.h> typedef struct edge { int node1,node2,wt; }edge; void sortedge(edge a[],int n) { int i,j; edge temp; for(i=0;i<n;i++) for(j=i+1;j<n;++j) if(a[i].wt>a[j].wt) { temp=a[i];a[i]=a[j];a[j]=temp; } } int check(int p[],int i,int j) { int v1,v2; v1=i; v2=j; while(p[i]>-1) i=p[i]; while(p[j]>-1) j=p[j]; if(i!=j) { p[j]=i; printf("%d->%dn",v1,v2); return 1; } return 0; } void main() { edge e[100]; int r[100],n,i,j,k=1,m,cost=0; clrscr(); printf("Kruskal algorithmn"); printf("Enter the no of nodes:"); scanf("%d",&n); for(i=0;i<n;i++) 64
  • 65. r[i]=-1; i=0; printf("nEnter no of edges:"); scanf("%d",&m); for(i=0;i<m;i++) { printf("nENter the edge and cost of the edge:"); scanf("%d%d%d",&e[i].node1,&e[i].node2,&e[i].wt); } sortedge(e,m); printf("nEdges of the MSTn"); i=0; while(k<n) { if(check(r,e[i].node1,e[i].node2)) { k++; cost=cost+e[i].wt; i++; } } printf("Minimum cost:%d",cost); getch(); } 65
  • 66. INPUT & OUTPUT: Kruskal algorithm Enter the no of nodes:4 Enter no of edges:4 Enter the edge and cost of the edge:1 2 1 Enter the edge and cost of the edge:1 3 3 Enter the edge and cost of the edge:2 3 2 Enter the edge and cost of the edge:2 4 1 Edges of the MST 1->2 2->4 2->3 Minimum cost:4 RESULT: 66
  • 67. Thus the program for implementation of kruskal’s algorithm has been completed successfully and output verified. Ex no – 14 IMPLEMENTATION OF BACKTRACKING ALGORITHM AIM: To write a c program to implement backtracking algorithm for Knapsack problem. ALGORITHM: Step1: Start the program. Step2: Include the required header files at the top of the program. Step3: Declare the function knap(), bound(). Step4: Get the input number of items and capacity of knapsack from user. Step5: Get the weight and profit for each item from user. Step6: In knap () function, the maximum capacity and profit are found Step7: In bound () function, the maximum capacity for inserting the item is checked. Step8: In main () method, the values of knapsack are printed in descending order. Step9: End of the program. 67
  • 68. PROGRAM: #include<stdio.h> #include<conio.h> int n,m,i,j,x[10],y[10]; float w[10],t,t1,t2,p[10],c1[10],b,c,fp=-1.0,fw; void knap(int,float,float); float bound(float,float,int); void main() { clrscr(); printf("nenter the no. of items : "); scanf("%d",&n); printf("nenter the maximum capacity of knapsack : "); scanf("%d",&m); for(i=1;i<=n;i++) { printf("nnenter the weight & profit : n"); scanf("%f%f",&w[i],&p[i]); } for(i=1;i<=n;i++) { for(j=i+1;j<=n;j++) { if(c1[i]>=c1[j]) t1=w[i]; w[i]=w[j]; w[j]=t1; t2=p[i]; p[i]=p[j]; p[j]=t2; t=c1[i]; c1[i]=c1[j]; c1[j]=t; } } printf("nnweightttprofitn"); for(i=1;i<=n;i++) { printf("n%ft%fn",w[i],p[i]); knap(1,0,0); printf("nnthe selected objects: "); for(i=1;i<=n;i++) { printf("%d",x[i]); 68
  • 69. } printf(“nFinal Weight=%0.2f”,fw); printf(“nFinal Profit=%0.2f”,fp); getch(); } void knap(int k,float cp,float cw) { if(cw+w[k]<=m) { y[k]=1; if(k<n) knap(k+1,cp+p[k],cw+w[k]); if((cp+p[k]>fp)&&(k==n)) { fp=cp+p[k]; fw=cw+w[k]; for(j=1;j<=n;j++) x[j]=y[j]; } if(bound(cp,cw,k)>=fp) { y[k]=0; if(k<n) knap(k+1,cp,cw); if((cp>fp)&&(k==n)) { fp=cp; fw=cw; for(j=1;j<=n;j++) x[j]=y[j]; }}}} float bound(float cp,float cw,int k) { float b=cp,c=cw; for(i=k+1;i<=n;i++) { c=c+w[i]; if(c<m) b=b+p[i]; else return(b+(1-(c-m))/w[i]*p[i]); } return b; } 69
  • 70. INPUT & OUTPUT: Enter the no. of items : 5 Enter the maximum capacity of knapsack : 20 Enter the weight & profit ; 3 12 Enter the weight & profit ; 2 4 Enter the weight & profit ; 4 8 Enter the weight & profit ; 5 10 Enter the weight & profit ; 4 12 Weight profit 4.000000 12.000000 5.000000 10.000000 4.000000 8.0000000 2.000000 4.0000000 3.000000 12.000000 The selected objects are: 11111 Final Weight=18.00 Final Profit=46.00 RESULT: 70
  • 71. Thus the program for implementation of backtracking algorithm for knapsack problem has been completed successfully and output verified. Ex no – 15 IMPLEMENTATION OF BRANCH AND BOUND ALGORITHM AIM: To write a c program to implement branch and bound algorithm for travelling salesman problem. ALGORITHM: Step1: Start the program. Step2: Include the required header files at the top of the program. Step3: Declare the function tsp(), display(). Step4: In main() method, get the number of cities and distance for each city from user. Step5: In tsp() function, finds the minimum distance from source. Step6: In display() function, minimum cost and path is displayed. Step7: End of the program. 71
  • 72. PROGRAM: #include<stdio.h> #include<conio.h> #define max 10 typedef struct { int nodes[max]; int vertex;int min; }path; path tsp(int src,path list,int ele[][max],int mcities) { int i,j; path nlist,npath,nmin; if(list.vertex==0) { nmin.min=ele[src][1]; nmin.nodes[mcities-1]=src; nmin.vertex=mcities; return nmin; } for(i=0;i<list.vertex;i++) { nlist.vertex=0; for(j=0;j<list.vertex;j++) if(i!=j) nlist.nodes[nlist.vertex++]=list.nodes[j]; npath=tsp(list.nodes[i],nlist,ele,mcities); npath.min=ele[src][list.nodes[i]]+npath.min; npath.nodes[mcities-list.vertex-1]=src; if(i==0) nmin=npath; else if(npath.min<nmin.min) nmin=npath; } return nmin; } void display(path path1) { int i; printf("nnthe minimum cost is %dn",path1.min); printf("nthe path is....n"); 72
  • 73. for(i=0;i<path1.vertex;i++) printf("%d--",path1.nodes[i]); printf("%d",path1.nodes[0]); } void main() { int i,j,ele[max][max],mcities; path graph,path1; clrscr(); printf("nenter number of cities : "); scanf("%d",&mcities); if(mcities==0) { printf("error : there is no city for proceeding the TSP"); } else { for(i=1;i<=mcities;i++) { for(j=1;j<=mcities;j++) if(i==j) ele[i][i]=0; else { printf("enter distance from city %d to %d [if no path put 999]: ",i,j); scanf("%d",&ele[i][j]); } if(i>1) graph.nodes[i-2]=i; } graph.vertex=mcities-1; path1=tsp(1,graph,ele,mcities); display(path1); } getch(); } 73
  • 74. INPUT & OUTPUT: Enter number of cities : 4 Enter distance from city 1 to 2 [if no path put 999]: 1 Enter distance from city 1 to 3 [if no path put 999]: 999 Enter distance from city 1 to 4 [if no path put 999]: 999 Enter distance from city 2 to 1 [if no path put 999]: 999 Enter distance from city 2 to 3 [if no path put 999]: 5 Enter distance from city 2 to 4 [if no path put 999]: 1 Enter distance from city 3 to 1 [if no path put 999]: 1 Enter distance from city 3 to 2 [if no path put 999]: 999 Enter distance from city 3 to 4 [if no path put 999]: 3 Enter distance from city 4 to 1 [if no path put 999]: 4 Enter distance from city 4 to 2 [if no path put 999]: 999 Enter distance from city 4 to 3 [if no path put 999]: 1 The minimum cost is 4 The path is….. 1---2---4---3---1 RESULT: 74
  • 75. Thus the program for implementation of branch and bound algorithm for travelling salesman problem has been completed successfully and output verified. Ex no –16 IMPLEMENTATION OF RANDOMIZED ALGORITHM AIM: To write a c program to implement randomized algorithm- to find repeated elements in the array. ALGORITHM: Step1: Start the program. Step2: Include the required header files at the top of the program. Step3: Declare the function repetition(). Step4: In main () method, used to print the repeated elements in the given array. Step5: Repetition () function, checks whether the declared array has repeated elements. Step6: End of the program. 75
  • 76. PROGRAM: #include<stdio.h> #include<conio.h> #include<stdlib.h> #include<time.h> int main(void) { int a[10]={10,20,30,40,11,12,13,10,30,30}; int n=10; void repetition(int a[],int n); clrscr(); printf("ntRANDOMIZED ALGORITHM - TO FIND REPEATED ELEMENTSn"); repetition(a,n); getch(); return 0; } void repetition(int a[],int n) { int i,j,count; time_t t; srand((unsigned)time(&t)); count=1; while(count<=100) { i=rand()%(n+1); j=rand()%(n+1); if((i!=j)&&(a[i]==a[j])) printf("nthe repeated element is present at index %d",i); count++; } } 76
  • 77. INPUT & OUTPUT: RANDOMIZED ALGORITHM – TO FIND REPEATED ELEMENTS The repeated element is present at index 9 The repeated element is present at index 9 The repeated element is present at index 2 The repeated element is present at index 0 The repeated element is present at index 0 The repeated element is present at index 7 The repeated element is present at index 7 The repeated element is present at index 9 The repeated element is present at index 7 The repeated element is present at index 9 RESULT: 77
  • 78. Thus the program for implementation of randomized algorithm to find repeated elements in the array has been completed successfully and output verified. 78